我正在尝试根据价格数据筛选股票列表。老实说,我真的不知道我在做什么,所以任何帮助都是非常感谢的。我会直奔主题。基本上,这个提示
select * from (
select symbol, name, stock_id, max(close), date
from stock_price join stock on stock.id = stock_price.stock_id
group by stock_id
order by symbol
) where date = '2021-04-01'
在DB浏览器(SQLite)中运行良好。在应用程序中,我希望它作为一个过滤器“新收盘高”工作:
import sqlite3, config
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from datetime import date
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/")
def index(request: Request):
stock_filter = request.query_params.get('filter', False)
connection = sqlite3.connect(config.DB_FILE)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
if stock_filter == 'new_closing_highs':
cursor.execute("""
select * from (
select symbol, name, stock_id, max(close), date
from stock_price join stock on stock.id = stock_price.stock_id
group by stock_id
order by symbol
) where date = ?
""", (date.today().isoformat(),))
else:
cursor.execute("""
SELECT id, symbol, name FROM stock order by symbol
""")
rows = cursor.fetchall()
return templates.TemplateResponse("index.html", {"request": request, "stocks": rows})
@app.get("/stock/{symbol}")
def index(request: Request, symbol):
connection = sqlite3.connect(config.DB_FILE)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute("""
SELECT id, symbol, name FROM stock WHERE symbol = ?
""", (symbol,))
row = cursor.fetchall()
cursor.execute("""
SELECT *FROM stock_price WHERE stock_ID = ? ORDER BY date DESC
""", (row['id'],))
prices = cursor.fetchall()
return templates.TemplateResponse("stock_detail.html", {"request": request, "stock": row, "bars": prices})
如果过滤器没有在代码中定义,它会跳回到所有股票,但它却显示了一个空表,我不知道为什么。
到目前为止,数据库有两个表:库存,包括Alpaca API提供的所有可交易的活跃资产:
id symbol name Exchange
65 AAA AAF First Priority CLO Bond ETF ARCA
66 AAAU Goldman Sachs Physical Gold ETF Shares ARCA
和股票价格:
id stock_id date open high low close volume
1 65 2020-10-02 24.9127 24.925 24.9127 24.92 2944
2 65 2020-10-05 24.91 24.94 24.91 24.92 29000
3 65 2020-10-06 24.89 24.91 24.89 24.91 4019
4 65 2020-10-07 24.9017 24.91 24.9 24.91 3800
5 65 2020-10-08 24.9 24.905 24.9 24.9 1534
6 65 2020-10-09 24.88 24.91 24.88 24.89 16273
请让我知道,如果我没有提供足够的信息在这里。非常感谢您抽出时间
2条答案
按热度按时间zqdjd7g91#
我不认为你的问题真的有用。
也许它对你拥有的数据和特定的日期
'2021-04-01'
碰巧有效。如果你想得到每只股票在某个特定日期的最高价格,你应该连接表,按股票分组和聚合:
mpbci0fu2#
我的错!我还没有今天的数据!我以为我有,但脚本没有按计划运行。我应该仔细检查一下。如果浪费了您的时间,非常抱歉