简体   繁体   English

Python图形属性错误

[英]Python Graphing Attribute Error

I edited the code with the suggestions and currently receive this error Traceback (most recent call last): File "C:\\Users\\Jonathan.HollowayMainPc\\Documents\\Inchimoku Kinko Hyo.py", line 111, in ichimoku_chart() File "C:\\Users\\Jonathan.HollowayMainPc\\Documents\\Inchimoku Kinko Hyo.py", line 97, in ichimoku_chart facecolor='green', alpha=0.2, interpolate=True) File "C:\\Python27\\lib\\site-packages\\matplotlib\\pyplot.py", line 2826, in fill_between interpolate=interpolate, **kwargs) File "C:\\Python27\\lib\\site-packages\\matplotlib\\axes_axes.py", line 4345, in fill_between raise ValueError("Argument dimensions are incompatible") ValueError: Argument dimensions are incompatible 我根据建议编辑了代码,当前收到此错误回溯(最近一次调用是最近的):ichimoku_chart()中的文件“ C:\\ Users \\ Jonathan.HollowayMainPc \\ Documents \\ Inchimoku Kinko Hyo.py”第111行文件“ C” :\\ Users \\ Jonathan.HollowayMainPc \\ Documents \\ Inchimoku Kinko Hyo.py“,第97行,位于ichimoku_chart facecolor ='green',alpha = 0.2,interpolate = True)文件“ C:\\ Python27 \\ lib \\ site-packages \\ matplotlib \\ pyplot.py“,第2826行,在fill_between interpolate = interpolate,** kwargs)文件“ C:\\ Python27 \\ lib \\ site-packages \\ matplotlib \\ axes_axes.py”,第4345行,在fill_between中,引发ValueError(”参数维数“不兼容”)ValueError:参数尺寸不兼容

My code is below not sure what is causing it. 我的代码在下面,不确定是什么原因造成的。 Any help would be appreciated. 任何帮助,将不胜感激。

import urllib
import string
import sys
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt
import pandas.io.data as web
import datetime
#from stooq_helper_functions import data_to_dataframe
stocks = []
#^ list of for stocks 
#for stock in stocks:
    #Everything gets tabbed here. 
stock = "ebay"

data = {'Close': [], 'High': [], 'Low': [], 'Open': [], 'Date':[], 'Volume':[]}
#^Above is done on each stock but only one for now to test. 
url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
page = urllib.urlopen(url)
for line in page:
    new_string = string.split(line, ',')
    if len(new_string) == 6:
        if new_string[0].isdigit() == True:
            #print new_string
            data[stock]= new_string
            todays_high = float(data[stock][2])
            todays_low = float(data[stock][3])
            todays_open = float(data[stock][4])
            todays_close = float(data[stock][1])
            todays_volume = data[stock][5]
            todays_date = data[stock][0]
            data['High'].append(todays_high)
            data['Low'].append(todays_low)
            data['Open'].append(todays_open)
            data['Date'].append(todays_date)
            data['Close'].append(todays_close)
            data['Volume'].append(todays_volume)

matplotlib.style.use('ggplot')


def ichimoku_chart():
    global data, stock
    # Prepare the data
    #pos = len(data) - days
    close_prices = pd.DataFrame(data['Close'])
    high_prices = pd.DataFrame(data['High'])
    low_prices = pd.DataFrame(data['Low'])
    data['Date'] = pd.to_datetime(data['Date'], format='%Y%m%d')
    # workaround, so matplotlib accepts date axis
    #data['Date'].set_index('Date')

    # Ichimoku chart components

    # 1. Tenkan-sen (Conversion Line): (9-period high + 9-period low)/2))
    period9_high = pd.rolling_max(high_prices, window=9)
    period9_low = pd.rolling_min(low_prices, window=9)
    tenkan_sen = (period9_high + period9_low) / 2
    data['tenkan_sen'] = tenkan_sen

    # 2. Kijun-sen (Base Line): (26-period high + 26-period low)/2))
    period26_high = pd.rolling_max(high_prices, window=26)
    period26_low = pd.rolling_min(low_prices, window=26)
    kijun_sen = (period26_high + period26_low) / 2
    data['kijun_sen'] = kijun_sen

    # 3. Senkou Span A (Leading Span A): (Conversion Line + Base Line)/2))
    # plotted 26 periods ahead
    senkou_span_a = ((tenkan_sen + kijun_sen) / 2).shift(26)
    data['senkou_span_a'] = senkou_span_a

    # 4. Senkou Span B (Leading Span B): (52-period high + 52-period low)/2))
    # plotted 22 periods ahead
    period52_high = pd.rolling_max(high_prices, window=52)
    period52_low = pd.rolling_min(low_prices, window=52)
    senkou_span_b = ((period52_high + period52_low) / 2).shift(22)
    data['senkou_span_b'] = senkou_span_b

    # 5. The most current closing price plotted 22 time periods behind
    chikou_span = close_prices.shift(-22)
    data['chikou_span'] = chikou_span

    #data = data[pos:]
    date_values = data['Date'].values

    fig = plt.figure()

    plt.plot_date(date_values, data['Close'], '-', linewidth=1.4, label='Close')
    plt.plot_date(date_values, data['tenkan_sen'], '-', label='Tenkan Sen')
    plt.plot_date(date_values, data['kijun_sen'], '-', label='Kijun Sen')
    plt.plot_date(date_values, data['senkou_span_a'], '-', linewidth=0)
    plt.plot_date(date_values, data['senkou_span_b'], '-', linewidth=0)
    plt.plot_date(date_values, data['chikou_span'], '-', label='Chikou Span')

    plt.fill_between(date_values, data['senkou_span_a'], data['senkou_span_b'],
                     where=data['senkou_span_a'] >= data['senkou_span_b'],
                     facecolor='green', alpha=0.2, interpolate=True)
    plt.fill_between(date_values, data['senkou_span_a'], data['senkou_span_b'],
                     where=data['senkou_span_a'] < data['senkou_span_b'],
                     facecolor='red', alpha=0.2, interpolate=True)

    fig.set_tight_layout(True)
    plt.legend(loc='upper left')
    plt.show()


#if __name__ == '__main__':
    #days = sys.argv[1]
    #stock = sys.argv[2]
    #ichimoku_chart(data_to_dataframe(stock + '.txt'), int(days))
ichimoku_chart()

There are multiple issues 有多个问题

  • url = url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1yr/csv' should be url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv' , ie range=1y instead of range=1yr . url = url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1yr/csv'应该是url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv' ,即range=1y而不是range=1yr Otherwise no data will be returned 否则将不返回任何数据
  • high_prices is a list but rolling_max expects a DataFrame ( http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_max.html ). high_prices是一个列表,但rolling_max需要一个DataFramehttp://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.rolling_max.html )。 Try high_prices = pd.DataFrame(data['High']) 试试high_prices = pd.DataFrame(data['High'])
  • Even with those two issues addressed, your plotting function plt.plot_date(date_values, data['Close'], '-', linewidth=1.4, label='Close') will fail because close_prices = data['Close'] will always be empty since no data is written to data['Close'] 即使解决了这两个问题,您的绘图函数plt.plot_date(date_values, data['Close'], '-', linewidth=1.4, label='Close')也会失败,因为close_prices = data['Close']将始终为空,因为没有数据写入data['Close']

Some smaller issues: 一些较小的问题:

  • todays_volume = data[stock][5] has a newline character \\n attached todays_volume = data[stock][5]带有换行符\\n
  • the line data[stock]= new_string is not needed, it is always overwritten by last read line data[stock]= new_string不需要,它总是被最后读取的行覆盖

Update for the edited code and new error message 更新已编辑的代码和新的错误消息

ValueError: Argument dimensions are incompatible ValueError:参数尺寸不兼容

If you look at the dimensions of your DataFrames you will see that they have different shapes. 如果查看DataFrames的尺寸,您会发现它们具有不同的形状。

>>> date_values.shape
(252,)
>>> data['senkou_span_a'].shape
(252, 1)

Changing your parameter to data['senkou_span_a'][0] will give a plot. 将您的参数更改为data['senkou_span_a'][0]将给出一个图。 I cannot tell whether the plot makes sense and shows the correct data but at least the Python statement is formally correct. 我无法判断该图是否有意义并显示正确的数据,但至少Python语句在形式上正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM