64 lines
2.1 KiB
Python
64 lines
2.1 KiB
Python
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)
|