prepare.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. from __future__ import annotations
  2. import httpx
  3. import collections
  4. import dataclasses
  5. import csv
  6. import json
  7. import sys
  8. import typing
  9. def main() -> None:
  10. (month,) = sys.argv[1:]
  11. with open(f'rawData/{month}.csv', 'r', newline='') as f:
  12. data = read_data(f)
  13. bases_data: dict[str, dict[str, int]] = {r.company_id: {'bases': r.num, 'rank': r.rank} for r in data['BASES']}
  14. with open(f'www/data/base-data-{month}.json', 'w') as f:
  15. json.dump(bases_data, f)
  16. ships_data: dict[str, dict[str, int]] = {r.company_id: {'ships': r.num, 'rank': r.rank} for r in data['SHIPS']}
  17. with open(f'www/data/ship-data-{month}.json', 'w') as f:
  18. json.dump(ships_data, f)
  19. with open(f'rawData/{month}-prices.json', 'r') as f:
  20. prices = get_prices(f)
  21. prod_data, company_data = get_prod_and_company_data(data, prices)
  22. with open(f'www/data/prod-data-{month}.json', 'w') as f:
  23. json.dump(prod_data, f)
  24. with open(f'www/data/company-data-{month}.json', 'w') as f:
  25. json.dump(company_data, f)
  26. response = httpx.get('https://api.fnar.net/material').raise_for_status()
  27. tickers = frozenset(mat['Ticker'] for mat in response.json() if mat['Ticker'] != 'CMK')
  28. if missing := tickers - prod_data.keys():
  29. print('warning: missing production data for tickers', missing)
  30. def read_data(f: typing.TextIO) -> dict[str, list[Row]]:
  31. data: dict[str, list[Row]] = collections.defaultdict(list)
  32. reader = csv.reader(f)
  33. for row in reader:
  34. data[row[0]].append(Row(int(row[1]), int(row[2]), row[3]))
  35. return data
  36. def get_prices(f: typing.TextIO) -> typing.Mapping[str, float]:
  37. raw_prices: typing.Sequence[Price] = json.load(f)
  38. volumes: dict[str, float] = collections.defaultdict(float)
  39. traded: dict[str, int] = collections.defaultdict(int)
  40. for price in raw_prices:
  41. if price['Traded30D'] is None:
  42. continue
  43. assert price['VWAP30D'] is not None
  44. volumes[price['MaterialTicker']] += price['VWAP30D'] * price['Traded30D']
  45. traded[price['MaterialTicker']] += price['Traded30D']
  46. prices = {ticker: volume / traded[ticker] for ticker, volume in volumes.items()}
  47. hardcoded_prices = {
  48. 'AFP': 65638,
  49. 'ANZ': 70601,
  50. 'ARP': 8457,
  51. 'BID': 55692,
  52. 'BFP': 23408,
  53. 'DD': 30111,
  54. 'GCH': 18303,
  55. 'GEN': 232097,
  56. 'GNZ': 30361,
  57. 'GWS': 9778478,
  58. 'HAM': 4686751,
  59. 'HNZ': 93580,
  60. 'IMM': 101522,
  61. 'JUI': 0,
  62. 'LU': 95730,
  63. 'PFG': 2677222,
  64. 'RDS': 598170,
  65. 'SDM': 1721027,
  66. 'SST': 5863587,
  67. 'SU': 157860,
  68. 'SUD': 84327,
  69. 'TAC': 245797,
  70. 'TOR': 540169,
  71. 'VCB': 673713,
  72. 'VFT': 1781416,
  73. 'VOE': 3699358,
  74. 'VOR': 2547315,
  75. 'VSC': 39446,
  76. }
  77. assert frozenset(prices).isdisjoint(hardcoded_prices), frozenset(prices).intersection(hardcoded_prices)
  78. prices.update(hardcoded_prices)
  79. return prices
  80. def get_prod_and_company_data(data: dict[str, list[Row]], prices: typing.Mapping[str, float]
  81. ) -> tuple[typing.Mapping[str, ProdData], typing.Mapping[str, typing.Any]]:
  82. prod: dict[str, ProdData] = {}
  83. individual: dict[str, dict[str, CompanyTickerData]] = collections.defaultdict(dict)
  84. totals: dict[str, CompanyTotals] = collections.defaultdict(lambda: {'volume': 0.0})
  85. for section, rows in data.items():
  86. if (ticker := get_production_ticker(section)) is None:
  87. continue
  88. price = prices[ticker]
  89. prod_amount = sum(row.num for row in rows) / 30
  90. prod[ticker] = {'amount': prod_amount, 'volume': prod_amount * price}
  91. for row in rows:
  92. amount = row.num / 30
  93. volume = amount * price
  94. individual[row.company_id][ticker] = {
  95. 'amount': amount,
  96. 'volume': volume,
  97. 'rank': row.rank,
  98. }
  99. totals[row.company_id]['volume'] += volume
  100. company_data = {'totals': add_company_ranks(totals), 'individual': dict(individual)}
  101. return prod, company_data
  102. def get_production_ticker(section: str) -> str | None:
  103. prefix = 'PRODUCTION_'
  104. suffix = '_DAYS_30'
  105. if not section.startswith(prefix) or not section.endswith(suffix):
  106. return None
  107. return section[len(prefix):-len(suffix)]
  108. def add_company_ranks(totals: dict[str, CompanyTotals]) -> dict[str, CompanyTotals]:
  109. ranked = sorted(totals.items(), key=lambda item: item[1]['volume'], reverse=True)
  110. for rank, (company_id, company_totals) in enumerate(ranked, start=1):
  111. company_totals['volumeRank'] = rank
  112. return totals
  113. @dataclasses.dataclass(frozen=True, slots=True, eq=False)
  114. class Row:
  115. rank: int
  116. num: int
  117. company_id: str
  118. class Price(typing.TypedDict):
  119. MaterialTicker: str
  120. VWAP30D: float | None
  121. Traded30D: int | None
  122. class ProdData(typing.TypedDict):
  123. amount: float
  124. volume: float
  125. class CompanyTickerData(typing.TypedDict):
  126. amount: float
  127. volume: float
  128. rank: int
  129. class CompanyTotals(typing.TypedDict, total=False):
  130. volume: float
  131. volumeRank: int
  132. if __name__ == '__main__':
  133. main()