PYTHON /PANDAS 错误值
PYTHON /PANDAS VALUEERROR
你好,我正在尝试用我从网上收集的一些数据制作一个交易机器人。但我总是得到 Valueerror 我的代码是为我完成的 我会尝试用 ploty 或其他东西来绘制它但我需要传递这个错误 first.if 你可以用macd 参数我会很高兴祝你有美好的一天。
import pandas as pd
import requests
import json
import plotly.graph_objs as go
from plotly.offline import plot
from pyti.exponential_moving_average import exponential_moving_average as ema
class TradingModel:
def __init__(self, symbol):
self.symbol = symbol
self.df = self.getData()
def getData(self):
base = 'https://api.binance.com'
endpoint = '/api/v1/klines'
params = '?&symbol=' + self.symbol + '&interval=1D'
url = base + endpoint + params
data = requests.get(url)
dictionary = json.loads(data.text)
df = pd.DataFrame.from_dict(dictionary)
df = df.drop(range(6, 12), axis=1)
col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
df.columns = col_names
for col in col_names:
df[col] = df[col].astype(float)
df['fast_ema'] = ema(df['close'].tolist(), 12)
df['slow_ema'] = ema(df['close'].tolist(), 26)
df['macd_line']= df['fast_ema']-df['slow_ema']
df['signal_line']= ema(df['macd_line'].tolist(),9)
df['histogram']=df['macd_line']-df['signal_line']
return df
def strategy(self):
df = self.df
buy_signals = []
for i in range(1, len(df['close'])):
if (df['macd_line'][i]>df['signal_line'][i]) & 1>df['histogram'][i]>0 :
buy_signals.append([df['time'][i], df['low'][i]])
self.plotData(buy_signals=buy_signals)
def plotData(self, buy_signals=False):
df = self.df
candle = go.Candlestick(
x=df['time'],
open=df['open'],
close=df['close'],
high=df['high'],
low=df['low'],
name="Candlesticks")
fsma = go.Scatter(
x=df['time'],
y=df['macd_line'],
name="Macd_line",
line=dict(color=('rgba(102, 207, 255, 50)')))
ssma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="Signal_line ",
line=dict(color=('rgba(255, 207, 102, 50)')))
hsma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="histogram ",
line=dict(color=('rgba(255, 207, 102, 50)')))
data = [candle, ssma, fsma,hsma]
if buy_signals:
buys = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] for item in buy_signals],
name="Buy Signals",
mode="markers",
)
sells = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] * 1.05 for item in buy_signals],
name="Sell Signals",
mode="markers",
)
data = [candle, ssma, fsma, hsma ,buys, sells]
layout = go.Layout(title=self.symbol)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename=self.symbol)
def Main():
symbol = "btcusdt"
model = TradingModel(symbol)
model.strategy()
if __name__ == '__main__':
Main()
我收到这个错误
C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\Scripts\python.exe C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py
Traceback (most recent call last):
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 125, in <module>
Main()
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 120, in Main
model = TradingModel(symbol)
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 14, in __init__
self.df = self.getData()
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 30, in getData
df = pd.DataFrame.from_dict(dictionary)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\frame.py", line 1247, in from_dict
return cls(data, index=index, columns=columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\frame.py", line 435, in __init__
mgr = init_dict(data, index, columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 254, in init_dict
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 64, in arrays_to_mgr
index = extract_index(arrays)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 355, in extract_index
raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
Process finished with exit code 1
我使用 json_normalize
而不是 from_dict
,当我打印 df 时,我得到的是:
df = pd.json_normalize(dictionary)
print(df)
code msg
0 -1100 Illegal characters found in parameter 'symbol'...
对吗?如果是,df = df.drop(range(6, 12), axis=1)
将不起作用,因为这些列不存在。
为您修复了代码:
import pandas as pd
import requests
import json
import plotly.graph_objs as go
from plotly.offline import plot
from pyti.exponential_moving_average import exponential_moving_average as ema
class TradingModel:
def __init__(self, symbol):
self.symbol = symbol
self.df = self.getData()
def getData(self):
base = 'https://api.binance.com'
endpoint = '/api/v1/klines'
params = '?&symbol=' + self.symbol + '&interval=1d'
url = base + endpoint + params
print(url)
data = requests.get(url)
dictionary = json.loads(data.text)
print(dictionary)
df = pd.DataFrame(dictionary)
print(df)
df = df.drop(range(6, 12), axis=1)
col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
df.columns = col_names
for col in col_names:
df[col] = df[col].astype(float)
df['fast_ema'] = ema(df['close'].tolist(), 12)
df['slow_ema'] = ema(df['close'].tolist(), 26)
df['macd_line']= df['fast_ema']-df['slow_ema']
df['signal_line']= ema(df['macd_line'].tolist(),9)
df['histogram']=df['macd_line']-df['signal_line']
return df
def strategy(self):
df = self.df
buy_signals = []
for i in range(1, len(df['close'])):
if (df['macd_line'][i]>df['signal_line'][i]) & 1>df['histogram'][i]>0 :
buy_signals.append([df['time'][i], df['low'][i]])
self.plotData(buy_signals=buy_signals)
def plotData(self, buy_signals=False):
df = self.df
candle = go.Candlestick(
x=df['time'],
open=df['open'],
close=df['close'],
high=df['high'],
low=df['low'],
name="Candlesticks")
fsma = go.Scatter(
x=df['time'],
y=df['macd_line'],
name="Macd_line",
line=dict(color=('rgba(102, 207, 255, 50)')))
ssma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="Signal_line ",
line=dict(color=('rgba(255, 207, 102, 50)')))
hsma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="histogram ",
line=dict(color=('rgba(255, 207, 102, 50)')))
data = [candle, ssma, fsma,hsma]
if buy_signals:
buys = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] for item in buy_signals],
name="Buy Signals",
mode="markers",
)
sells = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] * 1.05 for item in buy_signals],
name="Sell Signals",
mode="markers",
)
data = [candle, ssma, fsma, hsma ,buys, sells]
layout = go.Layout(title=self.symbol)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename=self.symbol)
def Main():
symbol = "BTCUSDT"
model = TradingModel(symbol)
model.strategy()
if __name__ == '__main__':
Main()
你好,我正在尝试用我从网上收集的一些数据制作一个交易机器人。但我总是得到 Valueerror 我的代码是为我完成的 我会尝试用 ploty 或其他东西来绘制它但我需要传递这个错误 first.if 你可以用macd 参数我会很高兴祝你有美好的一天。
import pandas as pd
import requests
import json
import plotly.graph_objs as go
from plotly.offline import plot
from pyti.exponential_moving_average import exponential_moving_average as ema
class TradingModel:
def __init__(self, symbol):
self.symbol = symbol
self.df = self.getData()
def getData(self):
base = 'https://api.binance.com'
endpoint = '/api/v1/klines'
params = '?&symbol=' + self.symbol + '&interval=1D'
url = base + endpoint + params
data = requests.get(url)
dictionary = json.loads(data.text)
df = pd.DataFrame.from_dict(dictionary)
df = df.drop(range(6, 12), axis=1)
col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
df.columns = col_names
for col in col_names:
df[col] = df[col].astype(float)
df['fast_ema'] = ema(df['close'].tolist(), 12)
df['slow_ema'] = ema(df['close'].tolist(), 26)
df['macd_line']= df['fast_ema']-df['slow_ema']
df['signal_line']= ema(df['macd_line'].tolist(),9)
df['histogram']=df['macd_line']-df['signal_line']
return df
def strategy(self):
df = self.df
buy_signals = []
for i in range(1, len(df['close'])):
if (df['macd_line'][i]>df['signal_line'][i]) & 1>df['histogram'][i]>0 :
buy_signals.append([df['time'][i], df['low'][i]])
self.plotData(buy_signals=buy_signals)
def plotData(self, buy_signals=False):
df = self.df
candle = go.Candlestick(
x=df['time'],
open=df['open'],
close=df['close'],
high=df['high'],
low=df['low'],
name="Candlesticks")
fsma = go.Scatter(
x=df['time'],
y=df['macd_line'],
name="Macd_line",
line=dict(color=('rgba(102, 207, 255, 50)')))
ssma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="Signal_line ",
line=dict(color=('rgba(255, 207, 102, 50)')))
hsma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="histogram ",
line=dict(color=('rgba(255, 207, 102, 50)')))
data = [candle, ssma, fsma,hsma]
if buy_signals:
buys = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] for item in buy_signals],
name="Buy Signals",
mode="markers",
)
sells = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] * 1.05 for item in buy_signals],
name="Sell Signals",
mode="markers",
)
data = [candle, ssma, fsma, hsma ,buys, sells]
layout = go.Layout(title=self.symbol)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename=self.symbol)
def Main():
symbol = "btcusdt"
model = TradingModel(symbol)
model.strategy()
if __name__ == '__main__':
Main()
我收到这个错误
C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\Scripts\python.exe C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py
Traceback (most recent call last):
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 125, in <module>
Main()
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 120, in Main
model = TradingModel(symbol)
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 14, in __init__
self.df = self.getData()
File "C:/Users/alper/PycharmProjects/tradingmodelpart1/tradingmodelpart1.py", line 30, in getData
df = pd.DataFrame.from_dict(dictionary)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\frame.py", line 1247, in from_dict
return cls(data, index=index, columns=columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\frame.py", line 435, in __init__
mgr = init_dict(data, index, columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 254, in init_dict
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 64, in arrays_to_mgr
index = extract_index(arrays)
File "C:\Users\alper\PycharmProjects\tradingmodelpart1\venv\lib\site-packages\pandas\core\internals\construction.py", line 355, in extract_index
raise ValueError("If using all scalar values, you must pass an index")
ValueError: If using all scalar values, you must pass an index
Process finished with exit code 1
我使用 json_normalize
而不是 from_dict
,当我打印 df 时,我得到的是:
df = pd.json_normalize(dictionary)
print(df)
code msg
0 -1100 Illegal characters found in parameter 'symbol'...
对吗?如果是,df = df.drop(range(6, 12), axis=1)
将不起作用,因为这些列不存在。
为您修复了代码:
import pandas as pd
import requests
import json
import plotly.graph_objs as go
from plotly.offline import plot
from pyti.exponential_moving_average import exponential_moving_average as ema
class TradingModel:
def __init__(self, symbol):
self.symbol = symbol
self.df = self.getData()
def getData(self):
base = 'https://api.binance.com'
endpoint = '/api/v1/klines'
params = '?&symbol=' + self.symbol + '&interval=1d'
url = base + endpoint + params
print(url)
data = requests.get(url)
dictionary = json.loads(data.text)
print(dictionary)
df = pd.DataFrame(dictionary)
print(df)
df = df.drop(range(6, 12), axis=1)
col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
df.columns = col_names
for col in col_names:
df[col] = df[col].astype(float)
df['fast_ema'] = ema(df['close'].tolist(), 12)
df['slow_ema'] = ema(df['close'].tolist(), 26)
df['macd_line']= df['fast_ema']-df['slow_ema']
df['signal_line']= ema(df['macd_line'].tolist(),9)
df['histogram']=df['macd_line']-df['signal_line']
return df
def strategy(self):
df = self.df
buy_signals = []
for i in range(1, len(df['close'])):
if (df['macd_line'][i]>df['signal_line'][i]) & 1>df['histogram'][i]>0 :
buy_signals.append([df['time'][i], df['low'][i]])
self.plotData(buy_signals=buy_signals)
def plotData(self, buy_signals=False):
df = self.df
candle = go.Candlestick(
x=df['time'],
open=df['open'],
close=df['close'],
high=df['high'],
low=df['low'],
name="Candlesticks")
fsma = go.Scatter(
x=df['time'],
y=df['macd_line'],
name="Macd_line",
line=dict(color=('rgba(102, 207, 255, 50)')))
ssma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="Signal_line ",
line=dict(color=('rgba(255, 207, 102, 50)')))
hsma = go.Scatter(
x=df['time'],
y=df['signal_line'],
name="histogram ",
line=dict(color=('rgba(255, 207, 102, 50)')))
data = [candle, ssma, fsma,hsma]
if buy_signals:
buys = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] for item in buy_signals],
name="Buy Signals",
mode="markers",
)
sells = go.Scatter(
x=[item[0] for item in buy_signals],
y=[item[1] * 1.05 for item in buy_signals],
name="Sell Signals",
mode="markers",
)
data = [candle, ssma, fsma, hsma ,buys, sells]
layout = go.Layout(title=self.symbol)
fig = go.Figure(data=data, layout=layout)
plot(fig, filename=self.symbol)
def Main():
symbol = "BTCUSDT"
model = TradingModel(symbol)
model.strategy()
if __name__ == '__main__':
Main()