如何使用 Pandas-matplotlib 绘制 Binance API Orderbook?

How to graph Binance API Orderbook with Pandas-matplotlib?

数据在 (orderbook = pd.DataFrame(orderbook_data):

之后的 3 列中
   timestamp                bids                      asks
 UNIX timestamp      [bidprice, bidvolume]   [askprice, askvolume]
        list has 100 values of each. timestamp is the same 

问题是我不知道如何 access/index 每行列表中的值 [price, volume] 每列

我知道 运行 ---> bids = orderbook["bids"]

我得到 100 个列表的列表 ---> [bidprice, bidvolume]

我希望避免循环....必须有一种方法来绘制数据

希望有人能理解我的问题。我只想在 x 上绘制价格,在 y 上绘制数量。目标是让它上线

由于您没有提供输入文件,我自己准备了:

timestamp;bids
1579082401;[123.12, 300]
1579082461;[135.40, 220]
1579082736;[130.76, 20]
1579082801;[123.12, 180]

为了阅读它,我使用了:

orderbook = pd.read_csv('Input.csv', sep=';')
orderbook.timestamp = pd.to_datetime(orderbook.timestamp, unit='s')

其内容为:

             timestamp           bids
0  2020-01-15 10:00:01  [123.12, 300]
1  2020-01-15 10:01:13  [135.40, 220]
2  2020-01-15 10:05:36   [130.76, 20]
3  2020-01-15 10:06:41  [123.12, 180]

现在:

  • timestamp 已转换为 pandasonic 类型的 datetime,
  • 但是bidsobject类型(实际上是string)。

并且,正如我所想,这与从您的输入文件中读取时相同。

现在是主要任务:第一步是从 bids 中提取两个数字, 将它们转换为 floatint 并保存在相应的列中:

orderbook = orderbook.join(orderbook.bids.str.extract(
    r'\[(?P<bidprice>\d+\.\d+), (?P<bidvolume>\d+)]'))
orderbook.bidprice = orderbook.bidprice.astype(float)
orderbook.bidvolume = orderbook.bidvolume.astype(int)

现在orderbook包含:

            timestamp           bids  bidprice  bidvolume
0 2020-01-15 10:00:01  [123.12, 300]    123.12        300
1 2020-01-15 10:01:01  [135.40, 220]    135.40        220
2 2020-01-15 10:05:36   [130.76, 20]    130.76         20
3 2020-01-15 10:06:41  [123.12, 180]    123.12        180

你可以生成例如散点图,调用:

orderbook.plot.scatter('bidprice', 'bidvolume');

或其他绘图函数。

另一种可能

或者您的orderbook_data可能是词典?类似于:

orderbook_data = {
    'timestamp': [1579082401, 1579082461, 1579082736, 1579082801],
    'bids': [[123.12, 300], [135.40, 220], [130.76, 20], [123.12, 180]] }

在这种情况下,当您从中创建 DataFrame 时,列类型 最初是:

  • 时间戳 - int64,
  • bids - 也是 object,但这次每个单元格都包含一个普通的 pythonic list.

然后你也可以将 timestamp 列转换为 datetime 就像 以上。

但要将 bidslists 的一列)拆分为 2 个单独的列, 你应该 运行:

orderbook[['bidprice', 'bidvolume']] = pd.DataFrame(orderbook.bids.tolist())

然后你有 2 个新列,分别包含 来源专栏,您可以像上面一样创建图形。