Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.49 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Nov 27 19:27:36 2019
  4.  
  5. @author: Administrator
  6. """
  7.  
  8.  
  9. import pandas as pd
  10.  
  11. import csv
  12. import sys
  13.  
  14. from collections import defaultdict, deque
  15.  
  16. class Trade():
  17. def __init__(self, time, symbol, buying, price, quantity, side):
  18. self.time = time
  19. self.symbol = symbol
  20. self.buying = buying
  21. self.price = price
  22. self.quantity = quantity
  23. self.side = side
  24.  
  25. class TradeManager():
  26. def __init__(self, store_trades=True, print_trades=False):
  27. self._open_trades = defaultdict(deque)
  28. self._closed_trades = []
  29. self._store_trades = store_trades
  30. self._print_trades = print_trades
  31. self._pnl = 0.0
  32. self.dict_of_symbols = {}
  33. self.dict_of_trades = {}
  34. self.count = 1
  35. self.qty_px_dict = {}
  36.  
  37. def process_trade(self, trade):
  38. d = self._open_trades[trade.symbol]
  39. #print(list(self._open_trades))
  40. if trade.symbol not in self.dict_of_symbols:
  41. self.dict_of_symbols[trade.symbol] = {'position':0, 'realized_pnl':0, 'avgpx':0}
  42. if trade.side ==1:
  43. self.dict_of_symbols[trade.symbol]['position'] += trade.quantity
  44. else:
  45. self.dict_of_symbols[trade.symbol]['position'] -= trade.quantity
  46.  
  47.  
  48.  
  49. # if no inventory, just add it
  50. if len(d) == 0:
  51. d.append(trade)
  52. return
  53.  
  54.  
  55. # if inventory exists, all trades must be same way (buy or sell)
  56. # if new trade is same way, again just add it
  57. if d[0].buying == trade.buying:
  58.  
  59. d.append(trade)
  60. return
  61.  
  62. print(trade.symbol, trade.price, trade.quantity, '\n')
  63.  
  64. # otherwise, consume the trades
  65. while len(d) > 0 and trade.quantity > 0:
  66. self.count +=1
  67. quant_traded = min(trade.quantity, d[0].quantity)
  68.  
  69. pnl = quant_traded * round(trade.price - d[0].price, 2)*50
  70.  
  71. # invert if we shorted
  72. if trade.buying:
  73. pnl *= -1
  74.  
  75. pnl = round(pnl, 2)
  76. self._pnl += pnl
  77.  
  78. if trade.symbol in self.dict_of_symbols:
  79. self.dict_of_symbols[trade.symbol]['realized_pnl'] += pnl
  80. # print(self.dict_of_symbols)
  81.  
  82. ct = ClosedTrade(d[0].time, trade.time, trade.symbol,
  83. quant_traded, pnl, d[0].buying, d[0].price, trade.price)
  84.  
  85. if self._print_trades:
  86. pass
  87. #print(ct)
  88. elif self._store_trades:
  89. self._closed_trades.append(ct)
  90.  
  91. trade.quantity -= quant_traded
  92. d[0].quantity -= quant_traded
  93.  
  94.  
  95. if d[0].quantity == 0:
  96. d.popleft()
  97.  
  98. for trade in d:
  99. # self.qty_px_dict.
  100. print(self.count)
  101. print(trade.symbol, trade.price, trade.quantity, trade.side, '\n')
  102.  
  103. # if the new trade still has quantity left over
  104. # then add it
  105. if trade.quantity > 0:
  106. d.append(trade)
  107.  
  108.  
  109.  
  110.  
  111.  
  112. def process_csv(self, file_name):
  113. #pull data outa of memory.
  114. # then run it with for loop.
  115. with open(file_name, 'r') as trades_csv:
  116. data = pd.read_csv(trades_csv)
  117. for key, tr in data.iterrows():
  118.  
  119. # 0 OrderID, 1 TransactTime, 2 ticker_2, 3 Side, 4 AvgPx, 5 CumQty
  120. buying = tr[3] == 1
  121. trade = Trade(tr[1], tr[2], buying,
  122. float(tr[4]), int(tr[5]), int(tr[3]))
  123.  
  124. self.process_trade(trade)
  125.  
  126.  
  127. def print_closed_trades(self):
  128. for ct in self._closed_trades:
  129. print(ct)
  130.  
  131.  
  132. def get_pnl(self):
  133.  
  134. return self._pnl
  135.  
  136. def manage_pos(self,data):
  137.  
  138. pass
  139.  
  140.  
  141.  
  142. class ClosedTrade():
  143. def __init__(self, open_t, close_t, symbol, quantity, pnl, bought_first,
  144. open_p, close_p):
  145. self.open_t = open_t
  146. self.close_t = close_t
  147. self.symbol = symbol
  148. self.quantity = quantity
  149. self.pnl = pnl
  150. self.bought_first = bought_first
  151. self.open_p = open_p
  152. self.close_p = close_p
  153. self.df = pd.DataFrame()
  154.  
  155. def __str__(self):
  156. s = "{},{},{},{},{:.2f},{},{},{:.2f},{:.2f}"
  157. s = s.format(
  158. self.open_t,
  159. self.close_t,
  160. self.symbol,
  161. self.quantity,
  162. self.pnl,
  163. "B" if self.bought_first else "S",
  164. "S" if self.bought_first else "B",
  165. self.open_p,
  166. self.close_p
  167. )
  168. #print(self.df)
  169.  
  170. return s
  171.  
  172.  
  173. if __name__ == "__main__":
  174. tm = TradeManager(store_trades=True, print_trades=True)
  175. print(("OPEN_TIME,CLOSE_TIME,SYMBOL,QUANTITY,PNL,"
  176. "OPEN_SIDE,CLOSE_SIDE,OPEN_PRICE,CLOSE_PRICE"))
  177. tm.process_csv(r"C:\FIX-master\FIX-master\grouped_fut_data.csv")
  178. print("{:.2f}".format(tm.get_pnl()))
  179.  
  180. #%%
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement