├── .gitignore ├── README.md ├── database.py ├── main.py ├── models.py ├── requirements.txt ├── run └── templates ├── home.html └── layout.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | 132 | *.db -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Didn't see a lot of examples out there for this framework, so decided to create one. 2 | 3 | ## Step 1: Hello World of FastAPI, Stub out the API endpoints 4 | 5 | * Display Hello World 6 | * Map out endpoints we will need, comment what they will do 7 | 8 | ## Step 2: Mock the UI with Semantic UI and Jinja2 Templates 9 | 10 | * Including CSS and JavaScript from the CDN 11 | 12 | ## Step 3: Database Design 13 | 14 | * To design our database, we create SQLAlchemy models 15 | * See what yfinance provides 16 | * forwardPE, forwardEps, dividendYield, 50 Day, 200 Day, Close 17 | * SQLAlchemy create_all 18 | 19 | ## Step 4: Add a stock endpoint 20 | 21 | * Background task to fetch info and add to db also 22 | * Use Insomnia to test it 23 | 24 | ## Step 5: Wire home screen 25 | 26 | * Show added stocks in a table 27 | 28 | ## Step 6: Filters to filter table 29 | 30 | * Filter boxes on UI 31 | * Use SQLALchemy to filter in db 32 | * Use query parameters to filter 33 | 34 | ## Step 7: Modal to add stock tickers via UI 35 | -------------------------------------------------------------------------------- /database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | SQLALCHEMY_DATABASE_URL = "sqlite:///./stocks.db" 6 | 7 | engine = create_engine( 8 | SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} 9 | ) 10 | 11 | SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) 12 | 13 | Base = declarative_base() -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import models 2 | import yfinance 3 | from fastapi import FastAPI, Request, Depends, BackgroundTasks 4 | from fastapi.templating import Jinja2Templates 5 | from database import SessionLocal, engine 6 | from pydantic import BaseModel 7 | from models import Stock 8 | from sqlalchemy.orm import Session 9 | 10 | app = FastAPI() 11 | 12 | models.Base.metadata.create_all(bind=engine) 13 | 14 | templates = Jinja2Templates(directory="templates") 15 | 16 | class StockRequest(BaseModel): 17 | symbol: str 18 | 19 | 20 | def get_db(): 21 | try: 22 | db = SessionLocal() 23 | yield db 24 | finally: 25 | db.close() 26 | 27 | 28 | @app.get("/") 29 | def home(request: Request, forward_pe = None, dividend_yield = None, ma50 = None, ma200 = None, db: Session = Depends(get_db)): 30 | """ 31 | show all stocks in the database and button to add more 32 | button next to each stock to delete from database 33 | filters to filter this list of stocks 34 | button next to each to add a note or save for later 35 | """ 36 | 37 | stocks = db.query(Stock) 38 | 39 | if forward_pe: 40 | stocks = stocks.filter(Stock.forward_pe < forward_pe) 41 | 42 | if dividend_yield: 43 | stocks = stocks.filter(Stock.dividend_yield > dividend_yield) 44 | 45 | if ma50: 46 | stocks = stocks.filter(Stock.price > Stock.ma50) 47 | 48 | if ma200: 49 | stocks = stocks.filter(Stock.price > Stock.ma200) 50 | 51 | stocks = stocks.all() 52 | 53 | return templates.TemplateResponse("home.html", { 54 | "request": request, 55 | "stocks": stocks, 56 | "dividend_yield": dividend_yield, 57 | "forward_pe": forward_pe, 58 | "ma200": ma200, 59 | "ma50": ma50 60 | }) 61 | 62 | 63 | def fetch_stock_data(id: int): 64 | 65 | db = SessionLocal() 66 | 67 | stock = db.query(Stock).filter(Stock.id == id).first() 68 | 69 | yahoo_data = yfinance.Ticker(stock.symbol) 70 | 71 | stock.ma200 = yahoo_data.info['twoHundredDayAverage'] 72 | stock.ma50 = yahoo_data.info['fiftyDayAverage'] 73 | stock.price = yahoo_data.info['previousClose'] 74 | stock.forward_pe = yahoo_data.info['forwardPE'] 75 | stock.forward_eps = yahoo_data.info['forwardEps'] 76 | stock.dividend_yield = yahoo_data.info['dividendYield'] * 100 77 | 78 | db.add(stock) 79 | db.commit() 80 | 81 | 82 | @app.post("/stock") 83 | async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): 84 | """ 85 | add one or more tickers to the database 86 | background task to use yfinance and load key statistics 87 | """ 88 | 89 | stock = Stock() 90 | stock.symbol = stock_request.symbol 91 | db.add(stock) 92 | db.commit() 93 | 94 | background_tasks.add_task(fetch_stock_data, stock.id) 95 | 96 | return { 97 | "code": "success", 98 | "message": "stock was added to the database" 99 | } 100 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Boolean, Column, ForeignKey, Numeric, Integer, String 2 | from sqlalchemy.orm import relationship 3 | 4 | from database import Base 5 | 6 | class Stock(Base): 7 | __tablename__ = "stocks" 8 | 9 | id = Column(Integer, primary_key=True, index=True) 10 | symbol = Column(String, unique=True, index=True) 11 | price = Column(Numeric(10, 2)) 12 | forward_pe = Column(Numeric(10, 2)) 13 | forward_eps = Column(Numeric(10, 2)) 14 | dividend_yield = Column(Numeric(10, 2)) 15 | ma50 = Column(Numeric(10, 2)) 16 | ma200 = Column(Numeric(10, 2)) -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | jinja2 4 | yfinance 5 | sqlalchemy -------------------------------------------------------------------------------- /run: -------------------------------------------------------------------------------- 1 | uvicorn main:app --reload -------------------------------------------------------------------------------- /templates/home.html: -------------------------------------------------------------------------------- 1 | {% extends "layout.html" %} 2 | 3 | {% block content %} 4 | 31 | 32 |

Filters

33 | 34 |
35 | 36 |
37 | 38 |
39 | 40 |
41 | 42 |
43 | 44 |
45 | 46 | 47 |
48 | 49 |
50 | 51 | 52 |
53 | 54 | 55 | 56 |
57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | {% for stock in stocks %} 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | {% endfor %} 85 | 86 |
SymbolPriceForward P/EForward EPSDividend Yield50 Day MA200 Day MA
{{ stock.symbol }}{{ stock.price }}{{ stock.forward_pe }}{{ stock.forward_eps }}{{ stock.dividend_yield }}{{ stock.ma50 }}{{ stock.ma200 }}
87 | 88 | 108 | 109 | {% endblock %} -------------------------------------------------------------------------------- /templates/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Stock Screener 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 |

Stock Screener

13 | {% block content %} 14 | {% endblock %} 15 |
16 | 17 | --------------------------------------------------------------------------------