繁体   English   中英

SQLAlchemy order_by公式结果

[英]SQLAlchemy order_by formula result

我是Python的新手。 基于 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM