我是Python的新手。基于this SO帖子,我使用PYODBC创建了一个SQL查询,以搜索历史期权价格的MSSQL表,并选择行使价最接近我指定的期望价格的期权符号。但是,我现在试图通过重构该程序来自学OOP,为此,我试图在SQLAlchemy中实现ORM。
我不知道如何实现计算的Order_By语句。我不认为计算所得的列会起作用,因为desired_strike是在每个方法调用时由user(me)指定的参数。
这是(简化的)原始代码:
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-wanted_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表达式对象或预期的字符串”-任何帮助将不胜感激。
最佳答案
order_by
需要一个字符串-给它:
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('abs(strike - %d)' % desired_strike)
关于python - SQLAlchemy order_by公式结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18412540/