由于数据帧错误,无法绘制实时数据

时间:2016-03-12 15:40:48

标签: python pandas matplotlib dataframe urllib2

我试图从Bit Coin网站绘制实时数据并且我得到了这个错误'ValueError:值的长度与索引的长度不匹配。我无法解决它。我假设这是因为我无法将不同长度的列添加到数据帧。任何人都可以帮忙吗?

我感谢任何帮助。

最好的问候,Inthan

import matplotlib
matplotlib.use("TkAgg")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style

import pandas as pd
import numpy as np

import urllib
import json

LARG_FONT =("Verdana", 12)
style.use('ggplot')

f = Figure(figsize = (5,5), dpi=100)
a = f.add_subplot(111)


def animate(i):
    dataLink = "https://btc-e.com/api/3/trades/btc_usd?limit=2000"
    data = urllib.request.urlopen(dataLink)
    data = data.readall().decode("utf-8")
    data = json.loads(data)
    data  = data["btc_usd"]
    data = pd.DataFrame(data)

    buys = data[(data['type']=="bid")]
    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    buyDates = (buys["datestamp"]).tolist()


    sells = data[(data['type']=="ask")]
    sells["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
    sellDates = (sells["datestamp"]).tolist()

    a.clear()
    a.plot_date(buyDates, buys["price"])
    a.plot_date(selfDates, sells["price"])


import tkinter as tk
from tkinter import ttk

class RealOptionApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.iconbitmap(self, default='') #Change icon of App
        tk.Tk.wm_title(self, "RealOptionApp")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand= True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames ={}

        for F in (StartPage, PageOne, BTCe_Page):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
            self.show_frame(StartPage)


    def show_frame(self, cont):

        frame=self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="StartPage", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Agree", command=lambda: controller.show_frame(BTCe_Page))
        button1.pack()


        button2 =ttk.Button(self, text="Disagree", command=quit)
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="PageOne", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 =ttk.Button(self, text="Go to BTCe_Page", command=lambda: controller.show_frame(BTCe_Page))
        button2.pack()



class BTCe_Page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label=ttk.Label(self, text="GraphPage", font=LARG_FONT)
        label.pack(pady=10, padx=10)

        button1 =ttk.Button(self, text="Back to PageOne", command=lambda: controller.show_frame(PageOne))
        button1.pack()

        button2 =ttk.Button(self, text="Back to Start Page", command=lambda: controller.show_frame(StartPage))
        button2.pack()


        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)


app = RealOptionApp()
ani = animation.FuncAnimation(f, animate, interval = 1000)
app.mainloop()

2 个答案:

答案 0 :(得分:1)

尝试更改以下行:

  

购买

_Name_

为:

buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
  

销售

buys["datestamp"] = pd.to_datetime(buys["timestamp"])

为:

sells["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")

并且您拼错了一个变量名称,因此请更改:

  

sellDates

sells["datestamp"] = pd.to_datetime(buys["datestamp"])

为:

a.plot_date(selfDates, sells["price"])

答案 1 :(得分:1)

我认为你的问题可以简化,因为可能会有更多的问题。

我可以帮助Pandas 您可以用于创建和过滤DataFrame个函数read_jsonto_datetime

如果您需要将timestamp列转换为date,请使用dt.date

import pandas as pd

#read json to dataframe and create df from dict column btc_usd
dataLink = "https://btc-e.com/api/3/trades/btc_usd?limit=2000"
data = pd.DataFrame([x for x in pd.read_json(dataLink)['btc_usd'] ])
#column timestamp converted to datetime
data['timestamp'] = pd.to_datetime(data['timestamp'], unit='s')
print data.head()
     amount    price       tid           timestamp type
0  0.020000  410.100  68313536 2016-03-12 16:28:14  ask
1  0.020000  410.100  68313535 2016-03-12 16:28:14  ask
2  0.307000  410.492  68313534 2016-03-12 16:28:10  ask
3  0.060000  410.492  68313533 2016-03-12 16:28:09  bid
4  0.189918  410.100  68313532 2016-03-12 16:28:08  ask

#filter data
buys = data[(data['type']=="bid")]
#get only date (remove time) to list
buyDates = buys["timestamp"].dt.date.tolist()

sells = data[(data['type']=="ask")]
#get only date (remove time) to list
sellDates = sells["timestamp"].dt.date.tolist()

print sells.head()
     amount    price       tid           timestamp type
0  0.020000  410.100  68313536 2016-03-12 16:28:14  ask
1  0.020000  410.100  68313535 2016-03-12 16:28:14  ask
2  0.307000  410.492  68313534 2016-03-12 16:28:10  ask
4  0.189918  410.100  68313532 2016-03-12 16:28:08  ask
5  0.010041  410.300  68313531 2016-03-12 16:28:08  ask

print sellDates[:5]
[datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12), datetime.date(2016, 3, 12)]

如果您需要所有Timestamp,则无需dt.date

sellDates = sells["timestamp"].tolist()
buyDates = buys["timestamp"].tolist()

print sellDates[:5]
[Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58'), Timestamp('2016-03-12 16:35:58')]