Skip to content

Commit

Permalink
feat: add return dictionary to backtest results
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-abuke committed Jun 26, 2024
1 parent f3505ee commit 571f235
Showing 1 changed file with 33 additions and 35 deletions.
68 changes: 33 additions & 35 deletions scripts/backtesting/main.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
import yfinance as yf
import backtrader as bt
import os, sys
# Assuming this script is two levels deep in the project directory

project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))
if project_root not in sys.path:
sys.path.append(project_root)

print("The project root is: ", os.getcwd())

from scripts.backtesting.analyzers.metrics_analyzer import MetricsAnalyzer
import scripts.backtesting.strategies as strategies
from scripts.backtesting.util.user_input import get_user_input
from scripts.backtesting.analyzers.metrics_analyzer import MetricsAnalyzer

def run_backtest(config):
initial_cash = 500
initial_cash = config['initial_cash']
start_date = config['start_date']
end_date = config['end_date']
ticker = config['stock_symbol']
indicator = config['indicator_symbol']
print("The config is: ",ticker, start_date, end_date, indicator)
ticker = config['ticker']
indicator = config['indicator']

# Fetch historical data
try:
data = yf.download(ticker, start=start_date, end=end_date)
Expand All @@ -34,27 +31,27 @@ def run_backtest(config):

# Add strategy based on selected indicator
if indicator == 'SMA':
from strategies.sma_strategy import SMAStrategy
from scripts.backtesting.strategies.sma_strategy import SMAStrategy
cerebro.addstrategy(SMAStrategy)
elif indicator == 'LSTM':
from strategies.lstm_strategy import LSTMStrategy
from scripts.backtesting.strategies.lstm_strategy import LSTMStrategy
cerebro.addstrategy(LSTMStrategy)
elif indicator == 'MACD':
from strategies.macd_strategy import MACDStrategy
from scripts.backtesting.strategies.macd_strategy import MACDStrategy
cerebro.addstrategy(MACDStrategy)
elif indicator == 'RSI':
from strategies.rsi_strategy import RSIStrategy
from scripts.backtesting.strategies.rsi_strategy import RSIStrategy
cerebro.addstrategy(RSIStrategy)
elif indicator == 'BB':
from strategies.bollinger_bands_strategy import BollingerBandsStrategy
elif indicator == 'Bollinger Bands':
from scripts.backtesting.strategies.bollinger_bands_strategy import BollingerBandsStrategy
cerebro.addstrategy(BollingerBandsStrategy)
else:
print("Invalid indicator selected.")
yield "Invalid indicator selected."
return

# Add analyzers
cerebro.addanalyzer(bt.analyzers.SharpeRatio, riskfreerate=0.0, annualized=True)
cerebro.addanalyzer(MetricsAnalyzer)
cerebro.addanalyzer(bt.analyzers.SharpeRatio, riskfreerate=0.0, _name='sharperatio')
cerebro.addanalyzer(MetricsAnalyzer, _name='MetricsAnalyzer')

# Run backtest
results = cerebro.run()
Expand All @@ -63,7 +60,7 @@ def run_backtest(config):
# Print results
print(f"Initial Cash: {initial_cash}")
print(f"Final Value: {cerebro.broker.getvalue()}")
print(f"Sharpe Ratio: {strat.analyzers.sharperatio.get_analysis()}")
print(f"Sharpe Ratio: {strat.analyzers.sharperatio.get_analysis()['sharperatio']}")

metrics_analyzer = strat.analyzers.getbyname('MetricsAnalyzer')
metrics = metrics_analyzer.get_analysis()
Expand All @@ -72,22 +69,23 @@ def run_backtest(config):
print(f"Winning Trades: {metrics['winning_trades']}")
print(f"Losing Trades: {metrics['losing_trades']}")

# return {
# 'initial_cash': initial_cash,
# 'final_value': cerebro.broker.getvalue(),
# 'sharpe_ratio': strat.analyzers.sharperatio.get_analysis(),
# 'return': metrics['return'],
# 'total_trades': metrics['trades'],
# 'winning_trades': metrics['winning_trades'],
# 'losing_trades': metrics['losing_trades']
# }
return {
'initial_cash': initial_cash,
'final_value': cerebro.broker.getvalue(),
'sharpe_ratio': strat.analyzers.sharperatio.get_analysis()['sharperatio'],
'percentage_return': metrics['return'],
'total_trades': metrics['trades'],
'winning_trades': metrics['winning_trades'],
'losing_trades': metrics['losing_trades']
}

if __name__ == "__main__":
# config = {
# 'start_date': '2020-01-01',
# 'end_date': '2021-01-01',
# 'stock_symbol': 'NVDA',
# 'indicator_symbol': 'SMA'
# }
config = get_user_input()
# initial_cash, start_date, end_date, ticker, indicator = get_user_input()
config = {
'initial_cash': 500,
'start_date': "2024-02-01",
'end_date': "2024-06-11",
'ticker': "NVDA",
'indicator': "SMA"
}
run_backtest(config)

0 comments on commit 571f235

Please sign in to comment.