Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- """
- Created on Wed Nov 27 19:27:36 2019
- @author: Administrator
- """
- import pandas as pd
- import csv
- import sys
- from collections import defaultdict, deque
- class Trade():
- def __init__(self, time, symbol, buying, price, quantity, side):
- self.time = time
- self.symbol = symbol
- self.buying = buying
- self.price = price
- self.quantity = quantity
- self.side = side
- class TradeManager():
- def __init__(self, store_trades=True, print_trades=False):
- self._open_trades = defaultdict(deque)
- self._closed_trades = []
- self._store_trades = store_trades
- self._print_trades = print_trades
- self._pnl = 0.0
- self.dict_of_symbols = {}
- self.dict_of_trades = {}
- self.count = 1
- self.qty_px_dict = {}
- def process_trade(self, trade):
- d = self._open_trades[trade.symbol]
- #print(list(self._open_trades))
- if trade.symbol not in self.dict_of_symbols:
- self.dict_of_symbols[trade.symbol] = {'position':0, 'realized_pnl':0, 'avgpx':0}
- if trade.side ==1:
- self.dict_of_symbols[trade.symbol]['position'] += trade.quantity
- else:
- self.dict_of_symbols[trade.symbol]['position'] -= trade.quantity
- # if no inventory, just add it
- if len(d) == 0:
- d.append(trade)
- return
- # if inventory exists, all trades must be same way (buy or sell)
- # if new trade is same way, again just add it
- if d[0].buying == trade.buying:
- d.append(trade)
- return
- print(trade.symbol, trade.price, trade.quantity, '\n')
- # otherwise, consume the trades
- while len(d) > 0 and trade.quantity > 0:
- self.count +=1
- quant_traded = min(trade.quantity, d[0].quantity)
- pnl = quant_traded * round(trade.price - d[0].price, 2)*50
- # invert if we shorted
- if trade.buying:
- pnl *= -1
- pnl = round(pnl, 2)
- self._pnl += pnl
- if trade.symbol in self.dict_of_symbols:
- self.dict_of_symbols[trade.symbol]['realized_pnl'] += pnl
- # print(self.dict_of_symbols)
- ct = ClosedTrade(d[0].time, trade.time, trade.symbol,
- quant_traded, pnl, d[0].buying, d[0].price, trade.price)
- if self._print_trades:
- pass
- #print(ct)
- elif self._store_trades:
- self._closed_trades.append(ct)
- trade.quantity -= quant_traded
- d[0].quantity -= quant_traded
- if d[0].quantity == 0:
- d.popleft()
- for trade in d:
- # self.qty_px_dict.
- print(self.count)
- print(trade.symbol, trade.price, trade.quantity, trade.side, '\n')
- # if the new trade still has quantity left over
- # then add it
- if trade.quantity > 0:
- d.append(trade)
- def process_csv(self, file_name):
- #pull data outa of memory.
- # then run it with for loop.
- with open(file_name, 'r') as trades_csv:
- data = pd.read_csv(trades_csv)
- for key, tr in data.iterrows():
- # 0 OrderID, 1 TransactTime, 2 ticker_2, 3 Side, 4 AvgPx, 5 CumQty
- buying = tr[3] == 1
- trade = Trade(tr[1], tr[2], buying,
- float(tr[4]), int(tr[5]), int(tr[3]))
- self.process_trade(trade)
- def print_closed_trades(self):
- for ct in self._closed_trades:
- print(ct)
- def get_pnl(self):
- return self._pnl
- def manage_pos(self,data):
- pass
- class ClosedTrade():
- def __init__(self, open_t, close_t, symbol, quantity, pnl, bought_first,
- open_p, close_p):
- self.open_t = open_t
- self.close_t = close_t
- self.symbol = symbol
- self.quantity = quantity
- self.pnl = pnl
- self.bought_first = bought_first
- self.open_p = open_p
- self.close_p = close_p
- self.df = pd.DataFrame()
- def __str__(self):
- s = "{},{},{},{},{:.2f},{},{},{:.2f},{:.2f}"
- s = s.format(
- self.open_t,
- self.close_t,
- self.symbol,
- self.quantity,
- self.pnl,
- "B" if self.bought_first else "S",
- "S" if self.bought_first else "B",
- self.open_p,
- self.close_p
- )
- #print(self.df)
- return s
- if __name__ == "__main__":
- tm = TradeManager(store_trades=True, print_trades=True)
- print(("OPEN_TIME,CLOSE_TIME,SYMBOL,QUANTITY,PNL,"
- "OPEN_SIDE,CLOSE_SIDE,OPEN_PRICE,CLOSE_PRICE"))
- tm.process_csv(r"C:\FIX-master\FIX-master\grouped_fut_data.csv")
- print("{:.2f}".format(tm.get_pnl()))
- #%%
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement