create a backtesting app which can do backtesting based on given the prompt, I will add by my self. the data fetching process for now use just use the code df = pd.read_csv('data.csv').
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a basic structure for a backtesting app in Python. This app will allow you to define your own strategy using a prompt (which you'll fill in later). For now, we'll focus on setting up the framework. We'll use Pandas for data manipulation, NumPy for numerical operations, and Matplotlib/Seaborn for visualizing the backtest results.
Backtesting App Structure
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Set seed for reproducibility
np.random.seed(42)
# Load data (for now, from a local CSV)
def load_data(file_path='data.csv'):
"""Loads historical data from a CSV file."""
try:
df = pd.read_csv(file_path)
df['Date'] = pd.to_datetime(df['Date']) # Assuming 'Date' column exists
df.set_index('Date', inplace=True)
return df
except Exception as e:
print(f"Failed to load data: {e}")
return None
# Strategy Base Class (you'll inherit from this)
class Strategy:
def __init__(self, data):
self.data = data
def generate_signals(self):
"""To be implemented by child classes. Should return a Series of signals."""
raise NotImplementedError("Subclass must implement generate_signals")
# Backtester Class
class Backtester:
def __init__(self, strategy, initial_capital=10000, fee=0.001):
"""
Initializes the Backtester.
:param strategy: An instance of Strategy (or its subclass)
:param initial_capital: Starting capital for the backtest
:param fee: Transaction fee (default: 0.1%)
"""
self.strategy = strategy
self.initial_capital = initial_capital
self.fee = fee
self.signals = None
self.trades = None
self.portfolio_values = None
def run(self):
"""Executes the backtest."""
self.signals = self.strategy.generate_signals()
self._generate_trades()
self._calculate_portfolio_values()
self._evaluate_performance()
def _generate_trades(self):
"""Converts signals into trades (executions)."""
trades = pd.DataFrame(index=self.signals.index)
trades['signal'] = self.signals
trades['position'] = trades['signal'].ffill() # Hold position until new signal
trades['trade'] = trades['position'].diff().fillna(0)
trades['trade'] = trades['trade'].apply(lambda x: 1 if x > 0 else (-1 if x < 0 else 0))
self.trades = trades
def _calculate_portfolio_values(self):
"""Simulates portfolio value over time."""
portfolio = pd.DataFrame(index=self.data.index)
portfolio['close'] = self.data['Close'] # Assuming 'Close' price column exists
portfolio['position'] = self.trades['position']
portfolio['cash'] = self.initial_capital - (portfolio['position'].shift(1) * portfolio['close'].shift(1) * self.trades['trade']).fillna(0).cumsum()
portfolio['stock_value'] = portfolio['position'] * portfolio['close']
portfolio['value'] = portfolio['cash'] + portfolio['stock_value']
portfolio['returns'] = portfolio['value'].pct_change().fillna(0)
self.portfolio_values = portfolio
def _evaluate_performance(self):
"""Computes key performance metrics."""
returns = self.portfolio_values['returns']
self.metrics = {
'Total Return': (self.portfolio_values['value'].iloc[-1] / self.initial_capital - 1) * 100,
'Annualized Return': ((1 + returns.mean()) ** 252 - 1) * 100,
'Volatility': returns.std() * np.sqrt(252) * 100,
'Sharpe Ratio': returns.mean() / returns.std() * np.sqrt(252),
'Max Drawdown': (self.portfolio_values['value'].cummax() - self.portfolio_values['value']).max() / self.portfolio_values['value'].cummax().max() * 100,
}
def plot_results(self):
"""Visualizes the backtest outcome."""
sns.set()
fig, axes = plt.subplots(nrows=3, figsize=(12, 10))
# Portfolio Value Over Time
self.portfolio_values['value'].plot(ax=axes[0], title='Portfolio Value Over Time', grid=True, legend=False)
# Position Holding (Long/Short/Cash)
self.trades['position'].plot(ax=axes[1], title='Position Held Over Time', grid=True, legend=False)
axes[1].fill_between(self.trades.index, self.trades['position'], where=(self.trades['position'] > 0), color='g', alpha=0.3)
axes[1].fill_between(self.trades.index, self.trades['position'], where=(self.trades['position'] < 0), color='r', alpha=0.3)
# Underlying Price with Buy/Sell Marks
axes[2].plot(self.data['Close'], label='Close Price', alpha=0.7)
buy_signals = self.trades[self.trades['trade'] > 0]
sell_signals = self.trades[self.trades['trade'] < 0]
axes[2].scatter(buy_signals.index, self.data.loc[buy_signals.index, 'Close'], label='Buy', marker='^', color='g')
axes[2].scatter(sell_signals.index, self.data.loc[sell_signals.index, 'Close'], label='Sell', marker='v', color='r')
axes[2].set_title('Underlying Price with Trades')
axes[2].legend()
axes[2].grid(True)
plt.tight_layout()
plt.show()
# Print performance metrics
print("\nPerformance Metrics:")
for metric, value in self.metrics.items():
print(f"{metric}: {value:.2f}")
# Example Strategy (Dummy)
class MyStrategy(Strategy):
def generate_signals(self):
"""Simple Moving Average Crossover Strategy."""
short_window = 40
long_window = 100
signals = pd.Series(index=self.data.index, name='signal')
signals.iloc[:long_window] = 0 # No signal initially
# Generate signals
self.data['SMA_short'] = self.data['Close'].rolling(window=short_window).mean()
self.data['SMA_long'] = self.data['Close'].rolling(window=long_window).mean()
signals[(self.data['SMA_short'] > self.data['SMA_long']) & (self.data['SMA_short'].shift(1) <= self.data['SMA_long'].shift(1))] = 1 # Buy
signals[(self.data['SMA_short'] < self.data['SMA_long']) & (self.data['SMA_short'].shift(1) >= self.data['SMA_long'].shift(1))] = -1 # Sell
return signals.fillna(0)
if __name__ == "__main__":
# Load data
data = load_data()
if data is not None:
# Initialize strategy
strategy = MyStrategy(data)
# Backtest
backtester = Backtester(strategy)
backtester.run()
backtester.plot_results()
How It Works:
load_data(): Loads historical market data from data.csv. Modify this function if your data source changes (e.g., API, database).
Strategy Class: Base class for all strategies. You’ll create subclasses (like MyStrategy) and implement generate_signals(). This method returns a Series of trading signals (1 for buy, -1 for sell, 0 for hold).
Backtester Class:
Initializes with a strategy instance, starting capital, and transaction fees.