【问题标题】:SQLAlchemy order_by formula resultSQLAlchemy order_by 公式结果
【发布时间】:2013-08-24 06:48:02
【问题描述】:

我是 Python 新手。基于this SO 帖子,我使用 PYODBC 创建了一个 SQL 查询来搜索历史期权价格的 MSSQL 表,并选择执行值最接近我指定的所需值的期权符号。但是,我现在正试图通过重构这个程序来自学 OOP,为此我正试图在 SQLAlchemy 中实现 ORM。

我不知道如何实现计算的 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

也许不是最 Pythonic,但它确实有效。我现在将我以前的程序代码封装到类中,并使用 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 expression object or string expected” - 任何帮助将不胜感激。

【问题讨论】:

    标签: python sql sql-server sqlalchemy


    【解决方案1】:

    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)
    

    【讨论】:

    • 谢谢!
    • 我已经编辑了我的问题以使其更清楚。是的,我绊倒了字符串格式的小问题,但修复后它仍然是 SQLAlchemy 的无效语法。
    • @AlanS 哦,你不需要 lambda :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多