Skip to content

Commit

Permalink
fix: backtesting features updated to resemble backend
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-abuke committed Jun 26, 2024
1 parent 7a60f98 commit ff05cf6
Show file tree
Hide file tree
Showing 3 changed files with 277 additions and 44 deletions.
147 changes: 146 additions & 1 deletion notebooks/backtesting.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,151 @@
"metrics = run_backtest({\"indicator_name\": \"SMA\", \"period\": 20}, df)\n",
"print(metrics)"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"c:\\Users\\user\\Downloads\\ten_academy\\week9\\Scalable_Backtesting_Infrastructure_for_Crypto_Trading\\notebooks\n"
]
}
],
"source": [
"import os\n",
"\n",
"print(os.getcwd())\n",
"os.chdir('..')"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The project root is: c:\\Users\\user\\Downloads\\ten_academy\\week9\\Scalable_Backtesting_Infrastructure_for_Crypto_Trading\n"
]
}
],
"source": [
"import yfinance as yf\n",
"import backtrader as bt\n",
"import os, sys\n",
"# from util.user_input import get_user_input\n",
"# Assuming this script is two levels deep in the project directory\n",
"# project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../'))\n",
"# if project_root not in sys.path:\n",
" # sys.path.append(project_root)\n",
"\n",
"print(\"The project root is: \", os.getcwd())\n",
"\n",
"from scripts.backtesting.analyzers.metrics_analyzer import MetricsAnalyzer\n",
"import scripts.backtesting.strategies as strategies\n",
"\n",
"def run_backtest(config):\n",
" initial_cash = 500\n",
" start_date = config['start_date']\n",
" end_date = config['end_date']\n",
" ticker = config['stock_symbol']\n",
" indicator = config['indicator_symbol']\n",
"\n",
" # Fetch historical data\n",
" try:\n",
" data = yf.download(ticker, start=start_date, end=end_date)\n",
" data_feed = bt.feeds.PandasData(dataname=data)\n",
" except Exception as e:\n",
" print(f\"Error fetching data: {e}\")\n",
" return\n",
"\n",
" # Initialize Cerebro engine\n",
" cerebro = bt.Cerebro()\n",
" cerebro.adddata(data_feed)\n",
" cerebro.broker.setcash(initial_cash)\n",
"\n",
" # Add strategy based on selected indicator\n",
" if indicator == 'SMA':\n",
" from strategies.sma_strategy import SMAStrategy\n",
" cerebro.addstrategy(SMAStrategy)\n",
" elif indicator == 'LSTM':\n",
" from strategies.lstm_strategy import LSTMStrategy\n",
" cerebro.addstrategy(LSTMStrategy)\n",
" elif indicator == 'MACD':\n",
" from strategies.macd_strategy import MACDStrategy\n",
" cerebro.addstrategy(MACDStrategy)\n",
" elif indicator == 'RSI':\n",
" from strategies.rsi_strategy import RSIStrategy\n",
" cerebro.addstrategy(RSIStrategy)\n",
" elif indicator == 'BB':\n",
" from strategies.bollinger_bands_strategy import BollingerBandsStrategy\n",
" cerebro.addstrategy(BollingerBandsStrategy)\n",
" else:\n",
" print(\"Invalid indicator selected.\")\n",
" yield \"Invalid indicator selected.\"\n",
"\n",
" # Add analyzers\n",
" cerebro.addanalyzer(bt.analyzers.SharpeRatio, riskfreerate=0.0, annualized=True)\n",
" cerebro.addanalyzer(MetricsAnalyzer)\n",
"\n",
" # Run backtest\n",
" results = cerebro.run()\n",
" strat = results[0]\n",
"\n",
" # Print results\n",
" print(f\"Initial Cash: {initial_cash}\")\n",
" print(f\"Final Value: {cerebro.broker.getvalue()}\")\n",
" print(f\"Sharpe Ratio: {strat.analyzers.sharperatio.get_analysis()}\")\n",
"\n",
" metrics_analyzer = strat.analyzers.getbyname('MetricsAnalyzer')\n",
" metrics = metrics_analyzer.get_analysis()\n",
" print(f\"Return: {metrics['return']}\")\n",
" print(f\"Total Trades: {metrics['trades']}\")\n",
" print(f\"Winning Trades: {metrics['winning_trades']}\")\n",
" print(f\"Losing Trades: {metrics['losing_trades']}\")\n",
"\n",
" return {\n",
" 'initial_cash': initial_cash,\n",
" 'final_value': cerebro.broker.getvalue(),\n",
" 'sharpe_ratio': strat.analyzers.sharperatio.get_analysis(),\n",
" 'return': metrics['return'],\n",
" 'total_trades': metrics['trades'],\n",
" 'winning_trades': metrics['winning_trades'],\n",
" 'losing_trades': metrics['losing_trades']\n",
" }"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<generator object run_backtest at 0x0000020846C944A0>"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"config = {\n",
" 'start_date': '2020-01-01',\n",
" 'end_date': '2021-01-01',\n",
" 'stock_symbol': 'NVDA',\n",
" 'indicator_symbol': 'SMA'\n",
"}\n",
"run_backtest(config)"
]
}
],
"metadata": {
Expand All @@ -699,7 +844,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
"version": "3.10.0"
}
},
"nbformat": 4,
Expand Down
Loading

0 comments on commit ff05cf6

Please sign in to comment.