roi.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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['building_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. for cx in ['AI1', 'CI1', 'IC1', 'NC1']:
  12. profits = calc_for_cx(cx, recipes, buildings, materials, raw_prices)
  13. with open(f'www/roi_{cx.lower()}.json', 'w') as f:
  14. json.dump([dataclasses.asdict(p) for p in profits], f, indent='\t')
  15. def calc_for_cx(cx: str, recipes: typing.Collection[Recipe], buildings: typing.Mapping[str, Building],
  16. materials: typing.Mapping[str, Material], raw_prices: typing.Collection[RawPrice]) -> typing.Sequence[Profit]:
  17. prices: dict[str, Price] = {
  18. p['MaterialTicker']: Price(p['VWAP7D'], p['AverageTraded7D'], p['VWAP30D']) for p in raw_prices # pyright: ignore[reportArgumentType]
  19. if p['ExchangeCode'] == cx
  20. }
  21. habitation: typing.Mapping[Worker, str] = {
  22. 'pioneers': 'HB1',
  23. 'settlers': 'HB2',
  24. 'technicians': 'HB3',
  25. 'engineers': 'HB4',
  26. 'scientists': 'HB5',
  27. }
  28. hab_area_cost: dict[Worker, float] = {}
  29. hab_capex: dict[Worker, float] = {}
  30. for worker, hab in habitation.items():
  31. hab_area_cost[worker] = buildings[hab]['area_cost'] / 100
  32. hab_capex[worker] = building_construction_cost(buildings[hab], prices) / 100
  33. profits: list[Profit] = []
  34. for recipe in recipes:
  35. if profit := calc_profit(recipe, buildings, hab_area_cost, hab_capex, materials, prices):
  36. profits.append(profit)
  37. profits.sort()
  38. return profits
  39. def calc_profit(recipe: Recipe, buildings: typing.Mapping[str, Building], hab_area_cost: typing.Mapping[Worker, float],
  40. hab_capex: typing.Mapping[Worker, float], materials: typing.Mapping[str, Material],
  41. prices: typing.Mapping[str, Price]) -> Profit | None:
  42. if len(recipe['outputs']) == 0:
  43. return
  44. outputs: list[MatPrice] = []
  45. revenue = 0
  46. output_prices: dict[str, PriceNonNull] = {}
  47. for output in recipe['outputs']:
  48. price = prices[output['material_ticker']]
  49. if price.vwap_7d is None or price.average_traded_7d is None:
  50. return # skip recipes with thinly traded outputs
  51. output_prices[output['material_ticker']] = typing.cast(PriceNonNull, price)
  52. outputs.append(MatPrice(output['material_ticker'], output['material_amount'], price.vwap_7d))
  53. revenue += price.vwap_7d * output['material_amount']
  54. input_costs: list[MatPrice] = []
  55. cost = 0
  56. for input in recipe['inputs']:
  57. if (input_cost := prices[input['material_ticker']].vwap_7d) is None:
  58. return # skip recipes with thinly traded inputs
  59. input_costs.append(MatPrice(input['material_ticker'], input['material_amount'], input_cost))
  60. cost += input_cost * input['material_amount']
  61. profit_per_run = revenue - cost
  62. building = buildings[recipe['building_ticker']]
  63. area = building['area_cost'] + sum(hab_area_cost[worker] * building[worker] for worker in hab_area_cost)
  64. capex = building_construction_cost(building, prices) + \
  65. sum(hab_capex[worker] * building[worker] for worker in hab_capex)
  66. runs_per_day = 24 * 60 * 60 * 1000 / recipe['time_ms']
  67. if building['building_ticker'] in ('FRM', 'ORC'):
  68. runs_per_day *= 1.1212 # promitor's fertility
  69. worker_consumable_daily_cost = building_daily_cost(building, prices)
  70. cost_per_day = cost * runs_per_day + worker_consumable_daily_cost
  71. lowest_liquidity = min(recipe['outputs'],
  72. key=lambda output: output['material_amount'] / output_prices[output['material_ticker']].average_traded_7d)
  73. output_per_day = lowest_liquidity['material_amount'] * runs_per_day
  74. logistics_per_area = max(
  75. sum(materials[input['material_ticker']]['weight'] * input['material_amount'] for input in recipe['inputs']),
  76. sum(materials[input['material_ticker']]['volume'] * input['material_amount'] for input in recipe['inputs']),
  77. sum(materials[output['material_ticker']]['weight'] * output['material_amount'] for output in recipe['outputs']),
  78. sum(materials[output['material_ticker']]['volume'] * output['material_amount'] for output in recipe['outputs']),
  79. ) * runs_per_day / area
  80. return Profit(outputs, recipe['recipe_name'],
  81. expertise=building['expertise'],
  82. profit_per_day=(profit_per_run * runs_per_day - worker_consumable_daily_cost),
  83. area=area,
  84. capex=capex,
  85. cost_per_day=cost_per_day,
  86. input_costs=input_costs,
  87. worker_consumable_cost_per_day=worker_consumable_daily_cost,
  88. runs_per_day=runs_per_day,
  89. logistics_per_area=logistics_per_area,
  90. output_per_day=output_per_day,
  91. average_traded_7d=output_prices[lowest_liquidity['material_ticker']].average_traded_7d)
  92. def building_construction_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  93. return sum(bc['material_amount'] * prices[bc['material_ticker']].vwap_7d for bc in building['costs']) # pyright: ignore[reportOperatorIssue]
  94. def building_daily_cost(building: Building, prices: typing.Mapping[str, Price]) -> float:
  95. consumption = {
  96. 'pioneers': [('COF', 0.5), ('DW', 4), ('RAT', 4), ('OVE', 0.5), ('PWO', 0.2)],
  97. 'settlers': [('DW', 5), ('RAT', 6), ('KOM', 1), ('EXO', 0.5), ('REP', 0.2), ('PT', 0.5)],
  98. 'technicians': [('DW', 7.5), ('RAT', 7), ('ALE', 1), ('MED', 0.5), ('SC', 0.1), ('HMS', 0.5), ('SCN', 0.1)],
  99. 'engineers': [('DW', 10), ('MED', 0.5), ('GIN', 1), ('FIM', 7), ('VG', 0.2), ('HSS', 0.2), ('PDA', 0.1)],
  100. 'scientists': [('DW', 10), ('MED', 0.5), ('WIN', 1), ('MEA', 7), ('NST', 0.1), ('LC', 0.2), ('WS', 0.1)],
  101. }
  102. cost = 0
  103. for worker, mats in consumption.items():
  104. workers = building[worker]
  105. for mat, per_100 in mats:
  106. mat_price = prices[mat]
  107. cost += (mat_price.vwap_7d or mat_price.vwap_30d) * workers * per_100 / 100
  108. return cost
  109. Worker = typing.Literal['pioneers', 'settlers', 'technicians', 'engineers', 'scientists']
  110. class Recipe(typing.TypedDict):
  111. recipe_name: str
  112. building_ticker: str
  113. inputs: list[RecipeMat]
  114. outputs: list[RecipeMat]
  115. time_ms: int
  116. class RecipeMat(typing.TypedDict):
  117. material_ticker: str
  118. material_amount: int
  119. class Building(typing.TypedDict):
  120. building_ticker: str
  121. expertise: str
  122. area_cost: int
  123. costs: list[BuildingMat]
  124. pioneers: int
  125. settlers: int
  126. technicians: int
  127. engineers: int
  128. scientists: int
  129. class BuildingMat(typing.TypedDict):
  130. material_ticker: str
  131. material_amount: int
  132. class Material(typing.TypedDict):
  133. ticker: str
  134. weight: float
  135. volume: float
  136. class RawPrice(typing.TypedDict):
  137. MaterialTicker: str
  138. ExchangeCode: str
  139. VWAP7D: float | None # volume-weighted average price over last 7 days
  140. AverageTraded7D: float | None # averaged daily traded volume over last 7 days
  141. VWAP30D: float | None
  142. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  143. class Price:
  144. vwap_7d: float | None
  145. average_traded_7d: float | None
  146. vwap_30d: float | None
  147. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  148. class PriceNonNull:
  149. vwap_7d: float
  150. average_traded_7d: float
  151. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  152. class Profit:
  153. outputs: typing.Collection[MatPrice]
  154. recipe: str
  155. expertise: str
  156. profit_per_day: float
  157. area: float
  158. capex: float
  159. cost_per_day: float
  160. input_costs: typing.Collection[MatPrice]
  161. worker_consumable_cost_per_day: float
  162. runs_per_day: float
  163. logistics_per_area: float
  164. output_per_day: float
  165. average_traded_7d: float
  166. def __lt__(self, other: Profit) -> bool:
  167. if (break_even := self.capex / self.profit_per_day) < 0:
  168. break_even = 10000 - self.profit_per_day
  169. if (other_break_even := other.capex / other.profit_per_day) < 0:
  170. other_break_even = 10000 - other.profit_per_day
  171. return break_even < other_break_even
  172. @dataclasses.dataclass(eq=False, frozen=True, slots=True)
  173. class MatPrice:
  174. ticker: str
  175. amount: int
  176. vwap_7d: float
  177. if __name__ == '__main__':
  178. main()