请帮忙 - 我一直收到以下Traceback错误:
当前正在运行Python 2.0
我试图使用Python的Plotly库显示展示比特币价格的信息图表。我已经尝试在代码顶部导入datetime,但似乎没有解决问题。
Traceback (most recent call last):
File "project_one.py", line 165, in <module>
crypto_price_df = get_crypto_data(coinpair)
File "project_one.py", line 155, in get_crypto_data
json_url = base_polo_url.format(poloniex_pair, start_date.timestamp(), end_date.timestamp(), pediod)
AttributeError: 'datetime.datetime' object has no attribute 'timestamp'
我的代码从这里开始
import numpy as np
import pandas as pd
from pandas import Series, DataFrame, Panel
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import seaborn as sns
import sklearn as sk
import scipy as sp
import os
import pickle
import quandl
import datetime
import plotly.plotly as py
import plotly.graph_objs as go
import plotly.figure_factory as ff
from plotly import tools
from plotly.offline import iplot, init_notebook_mode
from IPython.display import display, HTML
init_notebook_mode(connected=True)
def get_quandl_data(quandl_id):
cache_path = '{}.pkl'.format(quandl_id).replace('/','-')
try:
f = open(cache_path, 'rb')
df = pickle.load(f)
print('Loaded {} from cache'.format(quandl_id))
except (OSError, IOError) as e:
print('Downloading {} from Quandl'.format(quandl_id))
df = quandl.get(quandl_id, returns="pandas")
df.to_pickle(cache_path)
print('Cached {} at {}'.format(quandl_id, cache_path))
return df
btc_usd_price_kraken = get_quandl_data('BCHARTS/KRAKENUSD')
exchanges = ['COINBASE','BITSTAMP','ITBIT']
exchange_data = {}
exchange_data['KRAKEN'] = btc_usd_price_kraken
for exchange in exchanges:
exchange_code = 'BCHARTS/{}USD'.format(exchange)
btc_exchange_df = get_quandl_data(exchange_code)
exchange_data[exchange] = btc_exchange_df
def merge_dfs_on_column(dataframes, labels, col):
series_dict = {}
for index in range(len(dataframes)):
series_dict[labels[index]] = dataframes[index][col]
return pd.DataFrame(series_dict)
btc_usd_datasets = merge_dfs_on_column(list(exchange_data.values()),
list(exchange_data.keys()), 'Weighted Price')
def df_scatter(df, title, seperate_y_axis=False, y_axis_label='',
scale='linear', initial_hide=False):
label_arr = list(df)
series_arr = list(map(lambda col: df[col], label_arr))
layout = go.Layout(
title=title,
legend=dict(orientation="h"),
xaxis=dict(type='date'),
yaxis=dict(
title=y_axis_label,
showticklabels= not seperate_y_axis,
type=scale
)
)
y_axis_config = dict(
overlaying='y',
showticklabels=False,
type=scale )
visibility = 'visible'
if initial_hide:
visibility = 'legendonly'
trace_arr = []
for index, series in enumerate(series_arr):
trace = go.Scatter(
x=series.index,
y=series,
name=label_arr[index],
visible=visibility
)
if seperate_y_axis:
trace['yaxis'] = 'y{}'.format(index + 1)
layout['yaxis{}'.format(index + 1)] = y_axis_config
trace_arr.append(trace)
fig = go.Figure(data=trace_arr, layout=layout)
py.plot(fig)
df_scatter(btc_usd_datasets, 'Bitcoin Price (USD) By Exchange')
btc_usd_datasets.replace(0, np.nan, inplace=True)
df_scatter(btc_usd_datasets, 'Bitcoin Price (USD) By Exchange')
btc_usd_datasets['avg_btc_price_usd'] = btc_usd_datasets.mean(axis=1)
btc_trace = go.Scatter(x=btc_usd_datasets.index,
y=btc_usd_datasets['avg_btc_price_usd'])
py.plot([btc_trace])
def get_json_data(json_url, cache_path):
try:
f = open(cache_path, 'rb')
df = pickle.load(f)
print('Loaded {} from cache'.format(json_url))
except (OSError, IOError) as e:
print('Downloading {}'.format(json_url))
df = pd.read_json(json_url)
df.to_pickle(cache_path)
print('Cached {} at {}'.format(json_url, cache_path))
return df
# Helper Function that Generates Poloniex API HTTP requests
base_polo_url = 'https://poloniex.com/public?
command=returnChartData¤cyPair={}&start={}&end={}&period={}'
start_date = datetime.datetime.strptime('2015-01-01', '%Y-%m-%d') # get
data from the start of 2015
end_date = datetime.datetime.now() # up until today
pediod = 86400 # pull daily data (86,400 seconds per day)
def get_crypto_data(poloniex_pair):
json_url = base_polo_url.format(poloniex_pair, start_date.timestamp(), end_date.timestamp(), pediod)
data_df = get_json_data(json_url, poloniex_pair)
data_df = data_df.set_index('date')
return data_df
altcoins = ['ETH','LTC','XRP','ETC','STR','DASH','SC','XMR','XEM']
altcoin_data = {}
for altcoin in altcoins:
coinpair = 'BTC_{}'.format(altcoin)
crypto_price_df = get_crypto_data(coinpair)
altcoin_data[altcoin] = crypto_price_df
timestamp
方法是在 Python 3.3 中添加的。所以如果你使用的是 Python 2.0,甚至是 2.7 版本,你就没有这个方法。你需要从 PyPI 获取一个回溯版本,从 3.3 或更高版本的源代码中复制该函数(可能需要进行一些修改使其正常工作),使用第三方库,或者升级到现代的 Python 版本。 - abarnert