Skip to content

Commit

Permalink
Merge pull request 10Accademy-InsightStreamInc#11 from dev-abuke/main
Browse files Browse the repository at this point in the history
frontend
  • Loading branch information
dev-abuke authored Jun 22, 2024
2 parents d9e6d05 + 79f0970 commit 9c523d5
Show file tree
Hide file tree
Showing 24 changed files with 6,116 additions and 236 deletions.
165 changes: 165 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
mbacktesting/**
venv/
backtesting/**
backtest/**
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
2 changes: 1 addition & 1 deletion backend/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from sqlalchemy.orm import sessionmaker
import os

DATABASE_URL = os.getenv('DATABASE_URL', "postgresql+psycopg2://group_three:lbRFEbA2bf3g5x6iDRrIsNqLycCznpab@dpg-cp6uiansc6pc73cnh6f0-a.oregon-postgres.render.com/amharic_contents")
DATABASE_URL = os.getenv('DATABASE_URL', "postgresql://trading_db_av2v_user:210M6MA9QKEEgVdiasnUdMQDBNN417oy@dpg-cpqojbqj1k6c73bkqq3g-a.oregon-postgres.render.com/trading_db_av2v")

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Expand Down
33 changes: 29 additions & 4 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)
Expand All @@ -35,9 +42,22 @@ def read_indicators(skip: int = 0, limit: int = 10, db: Session = Depends(get_db
indicators = db.query(models.Indicator).offset(skip).limit(limit).all()
return indicators

@app.post('/stocks/', response_model=schemas.Stock)
def create_stock(stock: schemas.StockCreate, db: Session = Depends(get_db)):
db_stock = models.Stock(**stock.model_dump())
db.add(db_stock)
db.commit()
db.refresh(db_stock)
return db_stock

@app.get('/stocks/', response_model=List[schemas.Stock])
def read_stocks(skip: int = 0, limit: int = 20, db: Session = Depends(get_db)):
stocks = db.query(models.Stock).offset(skip).limit(limit).all()
return stocks

@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)
Expand Down Expand Up @@ -74,6 +94,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()
Expand Down
21 changes: 19 additions & 2 deletions backend/models.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,31 @@
from sqlalchemy import Column, Integer, Float, Date, ForeignKey, TIMESTAMP
from sqlalchemy import Column, Integer, Float, Date, ForeignKey, TIMESTAMP, String, Text, text
from sqlalchemy.orm import relationship
from .database import Base

class Indicator(Base):
__tablename__ = 'indicators'
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, unique=True)
symbol = Column(String, nullable=False, unique=True)
description = Column(Text)

class Stock(Base):
__tablename__ = 'stocks'
id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, unique=True)
symbol = Column(String, nullable=False, unique=True)
description = Column(Text)

class Scene(Base):
__tablename__ = 'scenes'
id = Column(Integer, primary_key=True, index=True)
period = Column(Integer, nullable=False)
start_date = Column(Date, nullable=False)
end_date = Column(Date, nullable=False)
stock_name = Column(String, ForeignKey('stocks.name'))
indicator_id = Column(Integer, ForeignKey('indicators.id'))
backtests = relationship('BacktestResult', back_populates='scene')
indicator = relationship('Indicator')

class BacktestResult(Base):
__tablename__ = 'backtest_results'
Expand All @@ -21,5 +38,5 @@ class BacktestResult(Base):
losing_trades = Column(Integer)
max_drawdown = Column(Float)
sharpe_ratio = Column(Float)
created_at = Column(TIMESTAMP, server_default='CURRENT_TIMESTAMP')
created_at = Column(TIMESTAMP, server_default=text('CURRENT_TIMESTAMP'))
scene = relationship('Scene', back_populates='backtests')
15 changes: 15 additions & 0 deletions backend/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

class IndicatorBase(BaseModel):
name: str
symbol: str
description: Optional[str] = None

class IndicatorCreate(IndicatorBase):
Expand All @@ -15,6 +16,20 @@ class Indicator(IndicatorBase):
class Config:
orm_mode = True

class StockBase(BaseModel):
name: Optional[str] = None
symbol: str
description: Optional[str] = None

class StockCreate(StockBase):
pass

class Stock(StockBase):
id: int

class Config:
orm_mode = True

class SceneBase(BaseModel):
period: int
start_date: date
Expand Down
47 changes: 47 additions & 0 deletions backend/utils/add_indicators_to_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import requests
import json

# URL of the API endpoint
url = "http://127.0.0.1:8000/indicators/"

# List of strategy indicators
indicators = [
{
"name": "Simple Moving Average",
"symbol": "SMA",
"description": "A simple, widely-used indicator that calculates the average of a selected range of prices, typically closing prices, by the number of periods in that range."
},
{
"name": "LSTM",
"symbol": "LSTM",
"description": "A type of recurrent neural network capable of learning long-term dependencies. Used for time-series forecasting due to its ability to remember information over long periods."
},
{
"name": "Moving Average Convergence Divergence",
"symbol": "MACD",
"description": "A trend-following momentum indicator that shows the relationship between two moving averages of a security’s price. It includes a MACD line, a signal line, and a histogram."
},
{
"name": "Relative Strength Index",
"symbol": "RSI",
"description": "A momentum oscillator that measures the speed and change of price movements. RSI oscillates between zero and 100, typically used to identify overbought or oversold conditions."
},
{
"name": "Bollinger Bands",
"symbol": "BB",
"description": "A volatility indicator that consists of a middle band (SMA) and two outer bands set two standard deviations away from the middle band. Used to identify overbought and oversold conditions."
}
]

# Headers for the POST request
headers = {
"Content-Type": "application/json"
}

# Iterate over the list of indicators and send POST requests
for indicator in indicators:
response = requests.post(url, data=json.dumps(indicator), headers=headers)
if response.status_code == 200:
print(f"Successfully added {indicator['name']}")
else:
print(f"Failed to add {indicator['name']}: {response.status_code} - {response.text}")
Loading

0 comments on commit 9c523d5

Please sign in to comment.