Python3:从Websocket中抓取数据并将其放入DataFrame中

时间:2018-03-24 00:09:13

标签: json python-3.x dataframe websocket

想知道是否有人可以提供帮助。我试图从websocket中获取数据并将其放入DataFrame,而不是每行都有多个字典。我用来从binance中提取的代码是:

from binance.client import Client
from binance.websockets import BinanceSocketManager
from binance.enums import *
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
from pandas.io.json import json_normalize

client = Client('api-key', 'api-secret')
tickers = client.get_all_tickers()


df = pd.DataFrame([])
count = 0
bm = None

### Multiplex socket

# Save incoming data
def process_message(msg):
    global count, df, bm
    print("stream: {} data: {}".format(msg['stream'], msg['data']))
    # append message to array

    df = df.append(msg, ignore_index=True)

    count += 1

    with open('klinesmultiplex_socket.csv', 'a') as f:
        df.to_csv(f, header=False)
    #df = pd.DataFrame(df)
    #df.to_csv('test.csv')


def initiate():
    global bm
    # Connect to client
    client = Client('api-key', 'api-secret')

    # Setup Socket
    bm = BinanceSocketManager(client)

    # then start the socket manager
    conn_key = bm.start_multiplex_socket(['bnbbtc@kline_1m', 'neobtc@kline_1m'], process_message)

    # start the socket
    bm.start()


initiate()

这就是在csv中保存的内容:

0,"{'e': 'kline', 'E': 1521847596412, 's': 'NEOBTC', 'k': {'t': 1521847560000, 'T': 1521847619999, 's': 'NEOBTC', 'i': '1m', 'f': 11202559, 'L': 11202604, 'o': '0.00765700', 'c': '0.00765900', 'h': '0.00766000', 'l': '0.00765400', 'v': '182.38000000', 'n': 46, 'x': False, 'q': '1.39674356', 'V': '131.09000000', 'Q': '1.00404646', 'B': '0'}}",neobtc@kline_1m
0,"{'e': 'kline', 'E': 1521847596412, 's': 'NEOBTC', 'k': {'t': 1521847560000, 'T': 1521847619999, 's': 'NEOBTC', 'i': '1m', 'f': 11202559, 'L': 11202604, 'o': '0.00765700', 'c': '0.00765900', 'h': '0.00766000', 'l': '0.00765400', 'v': '182.38000000', 'n': 46, 'x': False, 'q': '1.39674356', 'V': '131.09000000', 'Q': '1.00404646', 'B': '0'}}",neobtc@kline_1m
1,"{'e': 'kline', 'E': 1521847597055, 's': 'BNBBTC', 'k': {'t': 1521847560000, 'T': 1521847619999, 's': 'BNBBTC', 'i': '1m', 'f': 12744199, 'L': 12744341, 'o': '0.00132050', 'c': '0.00131530', 'h': '0.00132200', 'l': '0.00131500', 'v': '5571.10000000', 'n': 143, 'x': False, 'q': '7.33546205', 'V': '2637.29000000', 'Q': '3.47577851', 'B': '0'}}",bnbbtc@kline_1m
0,"{'e': 'kline', 'E': 1521847596412, 's': 'NEOBTC', 'k': {'t': 1521847560000, 'T': 1521847619999, 's': 'NEOBTC', 'i': '1m', 'f': 11202559, 'L': 11202604, 'o': '0.00765700', 'c': '0.00765900', 'h': '0.00766000', 'l': '0.00765400', 'v': '182.38000000', 'n': 46, 'x': False, 'q': '1.39674356', 'V': '131.09000000', 'Q': '1.00404646', 'B': '0'}}",neobtc@kline_1m

然而,我正在寻找它看起来像这样(甚至是为了摆脱第0列的价值......不确定那是什么):

   0, 'kline', 1521847596412, NEOBTC', 1521847560000, 1521847619999, 'NEOBTC', '1m', 11202559, 11202604, 0.00765700, 0.00765900, 0.00766000, 0.00765400, 182.38000000, 46, False, 1.39674356', 131.09000000, 1.00404646,0,neobtc@kline_1m
    0,'kline', 1521847596412, 'NEOBTC', 1521847560000, 1521847619999, 'NEOBTC', '1m', 11202559, 11202604, 0.00765700, 0.00765900, 0.00766000, 0.00765400, 182.38000000, 46, False, 1.39674356, 131.09000000, 1.00404646, 0,neobtc@kline_1m
    1,'kline', 1521847597055, 'BNBBTC', 1521847560000, 1521847619999, 'BNBBTC', '1m', 12744199, 12744341, 0.00132050, 0.00131530, 0.00132200, 0.00131500, 5571.10000000, 143, False, 7.33546205, 2637.29000000, 3.47577851, 0,bnbbtc@kline_1m
    0,'kline', 1521847596412, 'NEOBTC', 1521847560000, 1521847619999, 'NEOBTC', '1m', 11202559, 11202604,0.00765700, 0.00765900, 0.00766000, 0.00765400, 182.38000000, 46, False, 1.39674356, 131.09000000, 1.00404646, 0,neobtc@kline_1m

我已经尝试了很多东西,但无法让它工作:Json到DataFrame,DataFrame的多个词典,以及其他一些东西。如果我在正确的地方寻找,请告诉我。其中一些数字显示为'xxxx.xxxx',而不仅仅是xxxx.xxxx。

我最终想要做的是获取所有股票代码数据并将每个股票代码保存到上面的流中的单个文件中。即NEOBTC和BNBBTC将保存在他们自己的csv中。我只希望它在'x'时保存:但是,确实如此。

任何帮助都会在我的任何挣扎中受到高度赞赏,并感谢您花时间去研究这个问题。

2 个答案:

答案 0 :(得分:1)

在您当前的代码中,每次收到一条消息时,都会将其附加到DataFrame(附加到DataFrame的n.b.总是很慢,从来不是一个好主意)。然后,将DataFrame附加到该文件。因此,当您收到消息A,B和C时,您会写A,A,B,A,B,C。这是一个主要错误。

您的代码的另一个问题是没有理由为此使用Pandas。您应该使用内置的csv模块。像这样:

import csv
columns = ['e', 'E', 's', 'k'] # add whatever JSON keys you want
out = csv. DictWriter(open('klines.csv', 'wb'), columns)

然后为每条消息:

out.writerow(msg)

这将为您提供所需的输出格式(假设您添加了所需的所有列)。

如果您需要对每条消息执行所有操作,请将其写入CSV,您可以直接将writerow()函数作为API回调传递:

bm.start_multiplex_socket(['bnbbtc@kline_1m'], out.writerow)

这样您根本不需要process_message()

答案 1 :(得分:0)

from pprint import pprint

retorno = 0
retornoold = 0

def process_m_message(msg):
    global retorno    
    retorno = msg

conn_key = bm.start_multiplex_socket(connstr, process_m_message)
bm.start()

while True:
    if retorno != 0 and retorno != retornoold:        
        pprint(retorno)
        for x in range(0,len(retorno)):
            ...
    retornoold = retorno

这不是一个干净的解决方案,需要一些工作,但这是摆脱process_m_message的一种方法