我一次拍摄一张订单簿的快照,并在3D散点图上绘制每个快照。我的代码可以工作,但是我遇到了使用大量内存的问题。
如何优化它,以便仅绘制添加到数据框中的新点,从而避免出现此问题?
这是相关的代码段。
def orderbook_slice(market, xmin=20, xmax=20, ymax=20, graph=False):
orderbook = polo.returnOrderBook(str(market))
bid_price = list()
bid_amount = list()
ask_price = list()
ask_amount = list()
for i in range(len(orderbook['bids'])):
bid_price.append(orderbook['bids'][i][0])
bid_amount.append(orderbook['bids'][i][1])
ask_price.append(orderbook['asks'][i][0])
ask_amount.append(orderbook['asks'][i][1])
market_orderbook = pd.DataFrame({
'bid_price': bid_price,
'bid_amount': bid_amount,
'ask_price': ask_price,
'ask_amount': ask_amount,
}, dtype=np.float64)
market_orderbook['bid cum sum'] =np.cumsum(
market_orderbook['bid_price'].multiply(market_orderbook['bid_amount']))
market_orderbook['ask cum sum'] = np.cumsum(
market_orderbook['ask_price'].multiply(market_orderbook['ask_amount']))
market_orderbook['time'] = '{:%H:%M:%S}'.format(datetime.datetime.now())
x_min_lim = float(ask_price[xmin])
x_max_lim = float(bid_price[xmax])
if market_orderbook['bid cum sum'][ymax] > market_orderbook['ask cum sum'][ymax]:
y_max_lim = market_orderbook['bid cum sum'][ymax]
else:
y_max_lim = market_orderbook['ask cum sum'][ymax]
if (graph == True):
ax = market_orderbook.plot(kind='scatter', x='bid_price', y='bid cum sum', color='Green',
xlim=(x_min_lim, x_max_lim), ylim=(0, y_max_lim))
market_orderbook.plot(kind='scatter', x='ask_price', y='ask cum sum', color='Red', ax=ax)
plt.xticks(rotation=45)
market_orderbook['bid_price'] = market_orderbook['bid_price'].map('{:,.8f}'.format)
market_orderbook['ask_price'] = market_orderbook['ask_price'].map('{:,.8f}'.format)
market_orderbook['time_s'] = hms_to_s_converter(market_orderbook)
return market_orderbook
def hms_to_s_converter(df):
h, m, s = df['time'][0].split(':')
time = (int(h) * 60 * 60 + int(m) * 60 + int(s))
return time
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
orderbook = orderbook_slice(market)
for i in range(0,900):
ax.scatter(list(orderbook['bid_price'].astype(float)), list(orderbook['time_s'].astype(float)), list(orderbook['bid cum sum'].astype(float)), color='Green')
ax.scatter(list(orderbook['ask_price'].astype(float)), list(orderbook['time_s'].astype(float)), list(orderbook['ask cum sum'].astype(float)), color='Red')
orderbook = orderbook.append(orderbook_slice(market), ignore_index=True)
plt.pause(1)
plt.show()