diff --git a/backend/main.py b/backend/main.py index bacce15..11d906c 100644 --- a/backend/main.py +++ b/backend/main.py @@ -4,8 +4,15 @@ from . import models, schemas, database import pandas as pd import json +import os, sys -from utils.backtest import run_backtest +cwd=os.getcwd() +sys.path.append(f"{cwd}/backend/utils/") +sys.path.append(f"{cwd}/scripts/") + +print("The os is :: ", os.getcwd()) + +from backend.utils.backtest import run_backtest models.Base.metadata.create_all(bind=database.engine) @@ -20,11 +27,11 @@ def get_db(): @app.get('/health') def check_health(): - return "healthy" + return "API is healthy" @app.post('/indicators/', response_model=schemas.Indicator) def create_indicator(indicator: schemas.IndicatorCreate, db: Session = Depends(get_db)): - db_indicator = models.Indicator(**indicator.dict()) + db_indicator = models.Indicator(**indicator.model_dump()) db.add(db_indicator) db.commit() db.refresh(db_indicator) @@ -37,7 +44,7 @@ def read_indicators(skip: int = 0, limit: int = 10, db: Session = Depends(get_db @app.post('/scenes/', response_model=schemas.Scene) def create_scene(scene: schemas.SceneCreate, db: Session = Depends(get_db)): - db_scene = models.Scene(**scene.dict()) + db_scene = models.Scene(**scene.model_dump()) db.add(db_scene) db.commit() db.refresh(db_scene) @@ -74,6 +81,11 @@ def perform_backtest(scene_id: int, db: Session = Depends(get_db)): return backtest_results +@app.get('/run_backtest/', response_model=List[schemas.BacktestResult]) +def run_backtests(scene: schemas.SceneCreate, db: Session = Depends(get_db)): + db_scene = models.Scene(**scene.model_dump()) + return db_scene + @app.get('/backtest_results/', response_model=List[schemas.BacktestResult]) def read_backtest_results(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): backtest_results = db.query(models.BacktestResult).offset(skip).limit(limit).all() diff --git a/explain_stocs_py.txt b/explain_stocs_py.txt deleted file mode 100644 index fd94401..0000000 --- a/explain_stocs_py.txt +++ /dev/null @@ -1,40 +0,0 @@ -This code is a Python script for backtesting a simple moving average (SMA) trading strategy using the backtrader library. It includes the following components: - -1. Importing necessary libraries: - - The `backtrader` library for backtesting trading strategies. - - The `yf` library (yahoo finance) to download stock data from Yahoo Finance. - - The `pandas` library for data manipulation. - - The `datetime` module for working with dates and times. - -2. The `SMAStrategy` class: - - This class defines a simple trading strategy that uses a simple moving average (SMA) indicator. - - The strategy buys when the stock's closing price is above the SMA and sells when it's below. - - The strategy uses the `bt.indicators.SimpleMovingAverage` indicator to calculate the SMA. - -3. The `MetricsAnalyzer` class: - - This class is an analyzer that calculates and stores various metrics during the backtest, such as the initial and end cash, total number of trades, winning and losing trades, and return on investment. - - The analyzer uses the `notify_cashvalue`, `notify_trade`, and `get_analysis` methods to track and compute these metrics. - -4. The `get_user_input` function: - - This function prompts the user for input, including the initial cash, start and end dates for the backtest, and the stock ticker to analyze. - - The function also allows the user to select a stock from a predefined list of stocks. - -5. The `generate_unique_key` function: - - This function generates a unique key for each backtest run using the stock ticker, start date, and end date. - -6. The `save_results_to_csv` function: - - This function saves the backtest results to a CSV file. - -7. The `load_results_from_csv` function: - - This function loads the backtest results from the CSV file using the generated unique key. - -8. The `run_backtest` function: - - This function orchestrates the backtest process by calling other functions and classes. - - It first checks if the results for the given unique key already exist in the CSV file. - - If not, it downloads the stock data from Yahoo Finance, sets up the backtrader environment, and runs the backtest using the SMAStrategy and MetricsAnalyzer. - - The function then saves the results to a JSON file and prints the results to the console. - -9. The `if __name__ == '__main__'` block: - - This block loads the user input from a JSON configuration file and calls the `run_backtest` function to execute the backtest with the user-provided inputs. - -Overall, this script demonstrates a simple backtesting framework for evaluating the performance of a trading strategy over a specified period using historical stock data. \ No newline at end of file diff --git a/notebooks/backtesting.ipynb b/notebooks/backtesting.ipynb index 59d96cf..4c9643c 100644 --- a/notebooks/backtesting.ipynb +++ b/notebooks/backtesting.ipynb @@ -571,7 +571,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -646,7 +646,7 @@ }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 2, "metadata": {}, "outputs": [], "source": [ @@ -655,7 +655,7 @@ }, { "cell_type": "code", - "execution_count": 16, + "execution_count": 3, "metadata": {}, "outputs": [], "source": [ @@ -676,7 +676,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 9, "metadata": {}, "outputs": [ { @@ -689,7 +689,7 @@ { "data": { "text/plain": [ - "[{'Period': 25,\n", + "[{'Period': 20,\n", " 'Gross Profit': 866.7200000000012,\n", " 'Net Profit': 866.7200000000012,\n", " 'Number of Trades': 1,\n", @@ -699,13 +699,13 @@ " 'Sharpe Ratio': 1.0}]" ] }, - "execution_count": 21, + "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "run_backtest({\"indicator_name\": \"SMA\", \"period\": 25}, df)" + "run_backtest({\"indicator_name\": \"SMA\", \"period\": 20}, df)" ] } ], diff --git a/requirements..txt b/requirements..txt deleted file mode 100644 index 895a98d..0000000 --- a/requirements..txt +++ /dev/null @@ -1,6 +0,0 @@ -backtrader -seaborn -matplotlib -datetime -plotly -yfinance