roi.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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']) for p in raw_prices # pyright: ignore[reportArgumentType]
  13. if p['ExchangeCode'] == 'IC1' and p['VWAP7D'] is not None
  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. try:
  42. output_price = prices[output['Ticker']]
  43. cost = sum(prices[input['Ticker']].vwap * input['Amount'] for input in recipe['Inputs'])
  44. except KeyError: # skip recipes with thinly traded materials
  45. return
  46. revenue = output_price.vwap * output['Amount']
  47. building = buildings[recipe['BuildingTicker']]
  48. area = building['AreaCost'] + sum(hab_area_cost[worker] * building[worker] for worker in hab_area_cost)
  49. capex = building_construction_cost(building, prices) + \
  50. sum(hab_capex[worker] * building[worker] for worker in hab_capex)
  51. profit_per_run = revenue - cost
  52. runs_per_day = 24 * 60 * 60 * 1000 / recipe['TimeMs']
  53. if building['Ticker'] in ('FRM', 'ORC'):
  54. runs_per_day *= 1.1212 # promitor's fertility
  55. worker_consumable_daily_cost = building_daily_cost(building, prices)
  56. cost_per_day = cost * runs_per_day + worker_consumable_daily_cost
  57. output_per_day = output['Amount'] * runs_per_day
  58. logistics_per_area = max(
  59. sum(materials[input['Ticker']]['Weight'] * input['Amount'] for input in recipe['Inputs']),
  60. sum(materials[input['Ticker']]['Volume'] * input['Amount'] for input in recipe['Inputs']),
  61. materials[output['Ticker']]['Weight'] * output['Amount'],
  62. materials[output['Ticker']]['Volume'] * output['Amount'],
  63. ) * runs_per_day / area
  64. return Profit(output['Ticker'], recipe['RecipeName'],
  65. expertise=building['Expertise'].replace('_', ' ').lower(),
  66. profit_per_day=(profit_per_run * runs_per_day - worker_consumable_daily_cost),
  67. area=area,
  68. capex=capex,
  69. cost_per_day=cost_per_day,
  70. logistics_per_area=logistics_per_area,
  71. output_per_day=output_per_day,
  72. average_traded_7d=output_price.average_traded_7d)
  73. def building_construction_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  74. return sum(bc['Amount'] * prices[bc['CommodityTicker']].vwap for bc in building['BuildingCosts'])
  75. def building_daily_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  76. consumption = {
  77. 'Pioneers': [('COF', 0.5), ('DW', 4), ('RAT', 4), ('OVE', 0.5), ('PWO', 0.2)],
  78. 'Settlers': [('DW', 5), ('RAT', 6), ('KOM', 1), ('EXO', 0.5), ('REP', 0.2), ('PT', 0.5)],
  79. 'Technicians': [('DW', 7.5), ('RAT', 7), ('ALE', 1), ('MED', 0.5), ('SC', 0.1), ('HMS', 0.5), ('SCN', 0.1)],
  80. 'Engineers': [('DW', 10), ('MED', 0.5), ('GIN', 1), ('FIM', 7), ('VG', 0.2), ('HSS', 0.2), ('PDA', 0.1)],
  81. 'Scientists': [('DW', 10), ('MED', 0.5), ('WIN', 1), ('MEA', 7), ('NST', 0.1), ('LC', 0.2), ('WS', 0.1)],
  82. }
  83. cost = 0
  84. for worker, mats in consumption.items():
  85. workers = building[worker]
  86. for mat, per_100 in mats:
  87. cost += prices[mat].vwap * workers * per_100 / 100
  88. return cost
  89. Worker = typing.Literal['Pioneers', 'Settlers', 'Technicians', 'Engineers', 'Scientists']
  90. class Recipe(typing.TypedDict):
  91. RecipeName: str
  92. BuildingTicker: str
  93. Inputs: list[RecipeMat]
  94. Outputs: list[RecipeMat]
  95. TimeMs: int
  96. class RecipeMat(typing.TypedDict):
  97. Ticker: str
  98. Amount: int
  99. class Building(typing.TypedDict):
  100. Ticker: str
  101. Expertise: str
  102. AreaCost: int
  103. BuildingCosts: list[BuildingMat]
  104. Pioneers: int
  105. Settlers: int
  106. Technicians: int
  107. Engineers: int
  108. Scientists: int
  109. class BuildingMat(typing.TypedDict):
  110. CommodityTicker: str
  111. Amount: int
  112. class Material(typing.TypedDict):
  113. Ticker: str
  114. Weight: float
  115. Volume: float
  116. class RawPrice(typing.TypedDict):
  117. MaterialTicker: str
  118. ExchangeCode: str
  119. PriceAverage: int
  120. VWAP7D: float | None # volume-weighted average price over last 7 days
  121. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  122. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  123. class Price:
  124. vwap: float
  125. average_traded_7d: float
  126. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  127. class Profit:
  128. output: str
  129. recipe: str
  130. expertise: str
  131. profit_per_day: float
  132. area: float
  133. capex: float
  134. cost_per_day: float
  135. logistics_per_area: float
  136. output_per_day: float
  137. average_traded_7d: float
  138. def __lt__(self, other: Profit) -> bool:
  139. if (break_even := self.capex / self.profit_per_day) < 0:
  140. break_even = 10000 - self.profit_per_day
  141. if (other_break_even := other.capex / other.profit_per_day) < 0:
  142. other_break_even = 10000 - other.profit_per_day
  143. return break_even < other_break_even
  144. if __name__ == '__main__':
  145. main()