db.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from tinydb import TinyDB, Query
  2. import pandas as pd
  3. import numpy as np
  4. from scipy import stats
  5. import matplotlib.pyplot as plt
  6. from datetime import datetime,date
  7. MarketDB = TinyDB('market.json')
  8. PlayerDB = TinyDB('player.json')
  9. NotificationDB = TinyDB('notifications.json')
  10. MonitorDB = TinyDB('monitor_market.json')
  11. def getMonitor(card_name):
  12. data = MonitorDB.table('_default').all()
  13. for record in data:
  14. if record['name'] == card_name:
  15. return record['cost']
  16. return None
  17. def getDF(card=None,aDate=None,pruneOutliers=True):
  18. """
  19. Supply either a card identifier or a date for filter by.
  20. card can be an integer, which will pull from the card-num, or a string
  21. which will pull from the name field. It can also be a list of ints
  22. or strings, which will pull multiple cards histories.
  23. date can be either a datetime or string date formatted 'yyyy-mm-dd'
  24. """
  25. MarketDB = TinyDB('market.json')
  26. if card is not None:
  27. if isinstance(card,list):
  28. if isinstance(card[0],int):
  29. d=MarketDB.search(Query()['card-num'].one_of(card))
  30. else:
  31. d=MarketDB.search(Query()['name'].one_of(card))
  32. else:
  33. if isinstance(card,int):
  34. d=MarketDB.search(Query()['card-num']==card)
  35. else:
  36. d=MarketDB.search(Query()['name']==card)
  37. else:
  38. if isinstance(aDate,(datetime,date)):
  39. d=MarketDB.search(Query()['date']==aDate.strftime('%Y-%m-%d'))
  40. else:
  41. d=MarketDB.search(Query()['date']==aDate)
  42. df=pd.DataFrame(d)
  43. if pruneOutliers:
  44. df=df[np.abs(stats.zscore(df['cost'])) < 1.5]
  45. df.sort_values(by=['card-num','date'], ascending=[True,True], inplace=True)
  46. return df.round({'cost':2,'cost-min':0,'cost-max':0})
  47. def _hist(card=None,date=None,columns=['date','card-num','name','cost']):
  48. return getDF(card,date)[columns].to_string(index=False)
  49. def hist(card=None,date=None,columns=['date','card-num','name','cost']):
  50. print(_hist(card,date,columns))
  51. def plot(card=None,columns=['cost','cost-min','cost-max'],maxCost=None):
  52. """must use either card or date.
  53. card cand be card-num or name
  54. date can be a datetime type or a string like 'yyy-mm-dd'
  55. columns must be a list of any numeric fields in the MarketDB
  56. """
  57. df=getDF(card).plot(x='date',y=columns)
  58. plt.title(str(card))
  59. plt.xticks(rotation=45)
  60. plt.xlabel("Date")
  61. plt.ylabel("Cost")
  62. plt.ylim(0,maxCost)
  63. plt.show()
  64. def buyout():
  65. today=datetime.utcnow().strftime('%Y-%m-%d')
  66. PlayerDB = TinyDB('player.json')
  67. PlayerCards=PlayerDB.search(Query().fragment({'date':today}))
  68. Stock=[None]*152
  69. for card in PlayerCards: Stock[card['card-num']]=card['stock']
  70. MarketDF = getDF(aDate=today)
  71. MarketCards=MarketDF.to_dict('records')
  72. total=0
  73. cardCount=0
  74. NeededCards=[]
  75. print(f"Cards Needed Today:")
  76. print(f' Name Needed Cost')
  77. for card in MarketCards:
  78. if 'CRYSTAL' not in Stock[card['card-num']]:
  79. card['stock']=int(Stock[card['card-num']])
  80. card['needed']=10-card['stock']
  81. card['card-num']=card['card-num']
  82. card['total-cost']=card['needed']*card['cost']
  83. NeededCards.append(card)
  84. total+=card['total-cost']
  85. cardCount+=card['needed']
  86. print(f"{card['card-num']: >3} {card['name']: <20} {card['needed']: >2} {round(card['total-cost']): >5}")
  87. print(f" Remaining Cards: {cardCount}")
  88. print(f"Total Gems Needed: {round(total)}")