这是我能想到的股票代码数据库模型。我有两个表:stocks
,其主键为ticker
,prices
,其主键为date
:
Table stock
ticker name currency price
AAPL Apple, Inc. USD <reference to column AAPL in prices>
GOOG Google, Inc. USD <reference to column GOOG in prices>
Table prices
date AAPL GOOG
2015-03-28 1.01 0.99
2015-03-29 1.02 0.97
2015-03-30 1.01 0.98
通过这样的设置,我可以查询股票的价格历史,或者查询给定日期内所有股票的价格。
从ORM教程中推断,我对如何定义Stock
模型非常有信心:
<!-- language-all: lang-python -->
from sqlalchemy import Column, String, Float
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Stock(Base):
__tablename__ = 'stocks'
ticker = Column(String)
name = Column(String)
currency = Column(String)
price = # Not sure about this
但是,我不确定如何建模prices
。我已经尝试过建模一对多关系,但它没有抓住我想要的东西。我已经阅读过关于多对多关系的内容,但也不是这样。怎么做?或者这种数据结构是否不符合ORM范式?
我可以建模这种关系的另一种方法是使Stock
实例可以调用:
class Stock(Base):
__tablename__ = 'stocks'
ticker = Column(String)
name = Column(String)
currency = Column(String)
@decorator_that_indicates_database_session
def __call__(self, start_date, end_date=None):
# validate start_date and end_date here (for safety)
s = 'SELECT {0} WHERE date >= {1} AND date <= {2} FROM prices'
s = s.format(self.ticker, start_date, end_date)
ret = session.execute(s)
# Do stuff with `ret`
return zip(dates, prices)