1
我是Python中的新手。基于this SO贴子,我使用PYODBC创建了一个SQL查询来搜索具有历史期权价格的MSSQL表格,并选择具有最接近我指定的期望值的走势值的期权符号。但是,我现在试图通过重新设计这个程序来教自己OOP,为此我试图在SQLAlchemy中实现ORM。SQLAlchemy order_by公式结果
我无法弄清楚如何实现一个计算的Order_By语句。我不认为计算列会起作用,因为desired_strike是由用户(我)在每次方法调用时指定的参数。
这里是(简化)原代码:
import pyodbc
def get_option_symbol(stock, entry_date, exp_date, desired_strike):
entry_date = entry_date.strftime('%Y-%m-%d %H:%M:%S')
exp_date = exp_date.strftime('%Y-%m-%d %H:%M:%S')
cursor.execute("""select top(1) optionsymbol
from dbo.options_pricestore
where underlying=?
and quotedate=?
and expiration=?
and exchange='*'
and option_type=?
order by abs(strike - ?)""",
stock,
entry_date,
exp_date,
desired_strike,
)
row = cursor.fetchone()
return row
也许不是最Python化,但它的工作。我现在将以前的过程代码封装到类中,并使用SQLAlchemy的ORM,除了在这种情况下,我无法弄清楚如何在Order_By子句中表示abs(strike - desired_strike)。我没有使用lambda函数多过去,但这里是我想出了:
import sqlalchemy
class Option(Base):
__tablename__= 'options_pricestore'
<column definitions go here>
def get_option_symbol(stock, entry_date, exp_date, desired_strike):
entry_date = entry_date.strftime('%Y-%m-%d %H:%M:%S')
exp_date = exp_date.strftime('%Y-%m-%d %H:%M:%S')
qry = session.query(Option.optionsymbol).filter(and_
(Option.underlying == stock,
Option.quotedate == entry_date,
Option.expiration == exp_date,
Option.option_type== "put",
Option.exchange == "*")
).order_by(lambda:abs(Option.strike - desired_strike))
return qry
我得到“引发ArgumentError:SQL表达式对象或字符串预期” - 任何帮助将不胜感激。
<脸手掌的额头>谢谢! –
我编辑了我的问题,使其更加清晰。是的,我绊倒了一小部分字符串格式问题,但修正后仍然是无效的SQLAlchemy语法。 –
@AlanS哦,你不需要lambda :) – alecxe