roi.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from __future__ import annotations
  2. import dataclasses
  3. import json
  4. import typing
  5. import cache
  6. def main() -> None:
  7. recipes: list[Recipe] = cache.get('https://api.prunplanner.org/data/recipes')
  8. buildings: dict[str, Building] = {m['Ticker']: m for m in cache.get('https://api.prunplanner.org/data/buildings')}
  9. materials: dict[str, Material] = {m['Ticker']: m for m in cache.get('https://api.prunplanner.org/data/materials')}
  10. raw_prices: list[RawPrice] = cache.get('https://refined-prun.github.io/refined-prices/all.json')
  11. prices: dict[str, Price] = {
  12. p['MaterialTicker']: Price(p['VWAP7D'], p['AverageTraded7D'], p['VWAP30D']) for p in raw_prices # pyright: ignore[reportArgumentType]
  13. if p['ExchangeCode'] == 'IC1'
  14. }
  15. habitation: typing.Mapping[Worker, str] = {
  16. 'Pioneers': 'HB1',
  17. 'Settlers': 'HB2',
  18. 'Technicians': 'HB3',
  19. 'Engineers': 'HB4',
  20. 'Scientists': 'HB5',
  21. }
  22. hab_area_cost: dict[Worker, float] = {}
  23. hab_capex: dict[Worker, float] = {}
  24. for worker, hab in habitation.items():
  25. hab_area_cost[worker] = buildings[hab]['AreaCost'] / 100
  26. hab_capex[worker] = building_construction_cost(buildings[hab], prices) / 100
  27. profits: list[Profit] = []
  28. for recipe in recipes:
  29. if profit := calc_profit(recipe, buildings, hab_area_cost, hab_capex, materials, prices):
  30. profits.append(profit)
  31. profits.sort()
  32. with open('www/roi.json', 'w') as f:
  33. json.dump([dataclasses.asdict(p) for p in profits], f, indent='\t')
  34. def calc_profit(recipe: Recipe, buildings: typing.Mapping[str, Building], hab_area_cost: typing.Mapping[Worker, float],
  35. hab_capex: typing.Mapping[Worker, float], materials: typing.Mapping[str, Material],
  36. prices: typing.Mapping[str, Price]) -> Profit | None:
  37. try:
  38. (output,) = recipe['Outputs']
  39. except ValueError: # skip recipes that don't have exactly 1 output
  40. return
  41. output_price = prices[output['Ticker']]
  42. if output_price.vwap_7d is None or output_price.average_traded_7d is None: # skip recipes with thinly traded output
  43. return
  44. cost = 0
  45. for input in recipe['Inputs']:
  46. if (input_cost := prices[input['Ticker']].vwap_7d) is None:
  47. return # skip recipes with thinly traded inputs
  48. cost += input_cost * input['Amount']
  49. revenue = output_price.vwap_7d * output['Amount']
  50. building = buildings[recipe['BuildingTicker']]
  51. area = building['AreaCost'] + sum(hab_area_cost[worker] * building[worker] for worker in hab_area_cost)
  52. capex = building_construction_cost(building, prices) + \
  53. sum(hab_capex[worker] * building[worker] for worker in hab_capex)
  54. profit_per_run = revenue - cost
  55. runs_per_day = 24 * 60 * 60 * 1000 / recipe['TimeMs']
  56. if building['Ticker'] in ('FRM', 'ORC'):
  57. runs_per_day *= 1.1212 # promitor's fertility
  58. worker_consumable_daily_cost = building_daily_cost(building, prices)
  59. cost_per_day = cost * runs_per_day + worker_consumable_daily_cost
  60. output_per_day = output['Amount'] * runs_per_day
  61. logistics_per_area = max(
  62. sum(materials[input['Ticker']]['Weight'] * input['Amount'] for input in recipe['Inputs']),
  63. sum(materials[input['Ticker']]['Volume'] * input['Amount'] for input in recipe['Inputs']),
  64. materials[output['Ticker']]['Weight'] * output['Amount'],
  65. materials[output['Ticker']]['Volume'] * output['Amount'],
  66. ) * runs_per_day / area
  67. return Profit(output['Ticker'], recipe['RecipeName'],
  68. expertise=building['Expertise'],
  69. profit_per_day=(profit_per_run * runs_per_day - worker_consumable_daily_cost),
  70. area=area,
  71. capex=capex,
  72. cost_per_day=cost_per_day,
  73. logistics_per_area=logistics_per_area,
  74. output_per_day=output_per_day,
  75. average_traded_7d=output_price.average_traded_7d)
  76. def building_construction_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  77. return sum(bc['Amount'] * prices[bc['CommodityTicker']].vwap_7d for bc in building['BuildingCosts']) # pyright: ignore[reportOperatorIssue]
  78. def building_daily_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  79. consumption = {
  80. 'Pioneers': [('COF', 0.5), ('DW', 4), ('RAT', 4), ('OVE', 0.5), ('PWO', 0.2)],
  81. 'Settlers': [('DW', 5), ('RAT', 6), ('KOM', 1), ('EXO', 0.5), ('REP', 0.2), ('PT', 0.5)],
  82. 'Technicians': [('DW', 7.5), ('RAT', 7), ('ALE', 1), ('MED', 0.5), ('SC', 0.1), ('HMS', 0.5), ('SCN', 0.1)],
  83. 'Engineers': [('DW', 10), ('MED', 0.5), ('GIN', 1), ('FIM', 7), ('VG', 0.2), ('HSS', 0.2), ('PDA', 0.1)],
  84. 'Scientists': [('DW', 10), ('MED', 0.5), ('WIN', 1), ('MEA', 7), ('NST', 0.1), ('LC', 0.2), ('WS', 0.1)],
  85. }
  86. cost = 0
  87. for worker, mats in consumption.items():
  88. workers = building[worker]
  89. for mat, per_100 in mats:
  90. mat_price = prices[mat]
  91. cost += (mat_price.vwap_7d or mat_price.vwap_30d) * workers * per_100 / 100
  92. return cost
  93. Worker = typing.Literal['Pioneers', 'Settlers', 'Technicians', 'Engineers', 'Scientists']
  94. class Recipe(typing.TypedDict):
  95. RecipeName: str
  96. BuildingTicker: str
  97. Inputs: list[RecipeMat]
  98. Outputs: list[RecipeMat]
  99. TimeMs: int
  100. class RecipeMat(typing.TypedDict):
  101. Ticker: str
  102. Amount: int
  103. class Building(typing.TypedDict):
  104. Ticker: str
  105. Expertise: str
  106. AreaCost: int
  107. BuildingCosts: list[BuildingMat]
  108. Pioneers: int
  109. Settlers: int
  110. Technicians: int
  111. Engineers: int
  112. Scientists: int
  113. class BuildingMat(typing.TypedDict):
  114. CommodityTicker: str
  115. Amount: int
  116. class Material(typing.TypedDict):
  117. Ticker: str
  118. Weight: float
  119. Volume: float
  120. class RawPrice(typing.TypedDict):
  121. MaterialTicker: str
  122. ExchangeCode: str
  123. PriceAverage: int
  124. VWAP7D: float | None # volume-weighted average price over last 7 days
  125. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  126. VWAP30D: float | None
  127. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  128. class Price:
  129. vwap_7d: float | None
  130. average_traded_7d: float | None
  131. vwap_30d: float | None
  132. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  133. class Profit:
  134. output: str
  135. recipe: str
  136. expertise: str
  137. profit_per_day: float
  138. area: float
  139. capex: float
  140. cost_per_day: float
  141. logistics_per_area: float
  142. output_per_day: float
  143. average_traded_7d: float
  144. def __lt__(self, other: Profit) -> bool:
  145. if (break_even := self.capex / self.profit_per_day) < 0:
  146. break_even = 10000 - self.profit_per_day
  147. if (other_break_even := other.capex / other.profit_per_day) < 0:
  148. other_break_even = 10000 - other.profit_per_day
  149. return break_even < other_break_even
  150. if __name__ == '__main__':
  151. main()