Skip to content

Commit

Permalink
feat: add stocksget and post method
Browse files Browse the repository at this point in the history
  • Loading branch information
dev-abuke committed Jun 22, 2024
1 parent 67dfe95 commit 000ea19
Show file tree
Hide file tree
Showing 19 changed files with 5,930 additions and 184 deletions.
13 changes: 13 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ 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.model_dump())
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}")
97 changes: 97 additions & 0 deletions backend/utils/add_stocks_to db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import requests
import json

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

# List of companies
companies = [
{
"name": "Apple Inc",
"symbol": "AAPL",
"description": "Apple is a trillion-dollar company"
},
{
"name": "Microsoft Corporation",
"symbol": "MSFT",
"description": "Microsoft is a multinational technology company"
},
{
"name": "Amazon.com Inc",
"symbol": "AMZN",
"description": "Amazon is a multinational technology company focusing on e-commerce, cloud computing, and AI"
},
{
"name": "Alphabet Inc",
"symbol": "GOOGL",
"description": "Alphabet is the parent company of Google"
},
{
"name": "Facebook, Inc.",
"symbol": "FB",
"description": "Facebook is a social media and technology company"
},
{
"name": "Berkshire Hathaway Inc",
"symbol": "BRK.A",
"description": "Berkshire Hathaway is a multinational conglomerate holding company"
},
{
"name": "Tesla Inc",
"symbol": "TSLA",
"description": "Tesla is an electric vehicle and clean energy company"
},
{
"name": "Alibaba Group Holding Limited",
"symbol": "BABA",
"description": "Alibaba is a multinational conglomerate specializing in e-commerce, retail, Internet, and technology"
},
{
"name": "Tencent Holdings Limited",
"symbol": "TCEHY",
"description": "Tencent is a multinational conglomerate holding company"
},
{
"name": "Johnson & Johnson",
"symbol": "JNJ",
"description": "Johnson & Johnson is a multinational corporation focusing on medical devices, pharmaceuticals, and consumer goods"
},
{
"name": "Visa Inc",
"symbol": "V",
"description": "Visa is a multinational financial services corporation"
},
{
"name": "Walmart Inc",
"symbol": "WMT",
"description": "Walmart is a multinational retail corporation operating a chain of hypermarkets"
},
{
"name": "NVIDIA Corporation",
"symbol": "NVDA",
"description": "NVIDIA is a multinational technology company specializing in graphics processing units and AI"
},
{
"name": "Samsung Electronics Co Ltd",
"symbol": "SSNLF",
"description": "Samsung is a multinational conglomerate"
},
{
"name": "Procter & Gamble Co",
"symbol": "PG",
"description": "Procter & Gamble is a multinational consumer goods corporation"
}
]

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

# Iterate over the list of companies and send POST requests
for company in companies:
response = requests.post(url, data=json.dumps(company), headers=headers)
if response.status_code == 200:
print(f"Successfully added {company['name']}")
else:
print(f"Failed to add {company['name']}: {response.status_code} - {response.text}")
21 changes: 21 additions & 0 deletions frontend/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
24 changes: 24 additions & 0 deletions frontend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
8 changes: 8 additions & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# React + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
13 changes: 13 additions & 0 deletions frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
Loading

0 comments on commit 000ea19

Please sign in to comment.