我在SQLAlchemy中有一个ORM模型,它存储一些价格(按产品id和日期)和汇率(按货币起始、货币结束和日期)。我有一个返回查询对象的函数。查询包含id、date、currency和price列。可以选择将价格转换为另一种货币。我想将这个查询对象作为一个参数,并将它与ExRates
表连接起来,以转换成不同的货币。你知道吗
我使用的解决方法是读取需要pandas.DataFrame
和合并的部分。另一个棘手的部分是,有时我有一个星期六的价格,但没有汇率。在这种情况下,应使用最后可用的汇率。同样在pandas
中,我可以用.reindex
和.fillna(method='ffill')
来实现它,但我希望完全用SQL来实现它。你知道吗
以下是我的代码中的位供参考:
class Price(ReprMixin, GenFromDfMixin, ToDfMixin, Base):
__tablename__ = 'prices'
benchmark_id = Column(String, ForeignKey('benchmarks.benchmark_id'), index=True, primary_key=True)
date = Column(Date, index=True, primary_key=True)
price = Column(Float)
return_ytd = Column(Float)
class Benchmark(ReprMixin, GenFromDfMixin, ToDfMixin, Base):
__tablename__ = 'benchmarks'
benchmark_id = Column(String, primary_key=True)
index_name = Column(String)
currency = Column(String)
...
class ExRate(ReprMixin, GenFromDfMixin, ToDfMixin, Base):
__tablename__ = 'rates'
cur_from = Column(String, primary_key=True)
cur_to = Column(String, primary_key=True)
date = Column(Date, primary_key=True, index=True)
ex_rate = Column(Float)
def _query_by_id_and_date(benchmark_id, date_min=None, date_max=None):
if date_min is None:
date_min = datetime.date(1900, 1, 1)
if date_max is None:
date_max = datetime.date(2222, 1, 1)
prices = dal.session.query(Price.benchmark_id, Price.date, Price.price, Benchmark.currency).join(Benchmark)\
.filter(Price.benchmark_id == benchmark_id).filter(Price.date.between(date_min, date_max))
return prices
def _currency_convert(q, to_curr):
pass
# I would like to call this function like this:
# _currency_convert(_query_by_id_and_date('some_id'), 'EUR')
# and get the same 4 column query, but with prices converted to a new currency
我不确定我是否正确理解了你的问题。我想你们是在试图根据不同的货币来换算价格。试试看
相关问题 更多 >
编程相关推荐