Files
material-api/web/calculators/oil_92.py
2024-05-29 10:21:31 +08:00

64 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
from calculators import Calculator, Helper
from commons.models.oil import Oil
from commons.models.price_result import PriceResult
class Oil92Calculator(Calculator):
name = "汽油92"
material_id = "69.60.61.00"
unit = "kg"
spec = "92#"
def __init__(self, year, month):
self.year = year
self.month = month
def _get_network_price(self):
name_in = ('车用92号汽油ⅥB',)
# 获取上月末价格
previous_items = Oil.get_items(*Helper.get_last_month(self.year, self.month), name_in=name_in)
previous_item = previous_items[-1]
previous_price = previous_item.price
current_items = Oil.get_items(self.year, self.month, name_in=name_in)
# 从本月1号开始计算加权总数
start_date = datetime.date(self.year, self.month, 1)
previous_date = start_date
total_with_weight = 0
for item in current_items:
total_with_weight += previous_price * (item.date - previous_date).days
previous_price = item.price
previous_date = item.date
# 直到月末
end_date = datetime.date(*Helper.get_next_month(self.year, self.month), 1) - datetime.timedelta(days=1)
if end_date > previous_date:
total_with_weight += previous_price * (end_date - previous_date).days
# 计算
price = round(total_with_weight / (end_date - start_date).days) / 1000
fluctuating = price - int(getattr(self.previous_prices, 'price_network', price))
return round(price, 2), round(fluctuating, 2)
def _get_calculate_price(self, round_dit=2):
return super()._get_calculate_price(round_dit)
def _get_recommend_price(self):
return self.price_network, self.fluctuating_network
def save(self):
result = self.result()
PriceResult(**result).upsert()
if __name__ == '__main__':
from core.factory import ClientApp
with ClientApp().app_context():
calculator = Oil92Calculator(year=2023, month=11)
result = calculator.run()
calculator.save()
print(result)