2013-08-23 41 views
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表達式對象或字符串預期」 - 任何幫助將不勝感激。

回答

0

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) 
+0

<臉手掌的額頭>謝謝! –

+0

我編輯了我的問題,使其更加清晰。是的,我絆倒了一小部分字符串格式問題,但修正後仍然是無效的SQLAlchemy語法。 –

+0

@AlanS哦,你不需要lambda :) – alecxe