質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

2000閲覧

python株テクニカル指標のグラフ化について

o-fk

総合スコア32

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/11/07 05:28

移動平均、出来高、MACD、RSIの4つのグラフを出力したいのですが、エラー文と共に最後のRSIのみグラフが出てきません。エラー文もよくわからないので、どうしたらよいでしょうか。

import pandas as pd import numpy as np import talib as ta from pandas_datareader import data import matplotlib.pyplot as plt %matplotlib inline start = '2019-11-01' end = '2020-11-01' df = data.DataReader('^N225', 'yahoo', start, end) date = df.index close = df['Adj Close'] df['macd'], df['macdsignal'], df['macdhist'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) df['RSI'] = ta.RSI(close, timeperiod=span02) span01 = 5 span02 = 25 span03 = 50 df['mov01'] = close.rolling(window=span01).mean() df['mov02'] = close.rolling(window=span02).mean() df['mov03'] = close.rolling(window=span03).mean() plt.figure(figsize=(30,10)) plt.subplot(4,1,1) #移動平均 plt.plot(date,close,label='Close') plt.plot(date, df['mov01'],label='mov01') plt.plot(date, df['mov02'],label='mov02') plt.plot(date, df['mov03'],label='mov03') plt.legend() plt.subplot(4,1,2) #出来高 plt.bar(date, df['Volume'], label='Volume') plt.legend() plt.subplot(4,1,3) #MACD plt.fill_between(date, df['macdhist'], alpha=0.5, label='MACD_hist') plt.hlines(0, start, end, 'gray', linestyle='dashed') plt.legend() plt.subplot(4,1,4) #RSI plt.plot(date, df['RSI'], label='RSI') plt.ylim(0,100) plt.hlines([30,50,70], start, end, 'gray', linestyles='dashed') plt.legend()

エラー文は以下です。

AttributeError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\matplotlib\axis.py in convert_units(self, x) 1549 try: -> 1550 ret = self.converter.convert(x, self.units, self) 1551 except Exception as e: ~\Anaconda3\lib\site-packages\matplotlib\dates.py in convert(value, unit, axis) 2007 """ -> 2008 return date2num(value) 2009 ~\Anaconda3\lib\site-packages\matplotlib\dates.py in date2num(d) 425 return d --> 426 return _to_ordinalf_np_vectorized(d) 427 ~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in __call__(self, *args, **kwargs) 2107 -> 2108 return self._vectorize_call(func=func, args=vargs) 2109 ~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in _vectorize_call(self, func, args) 2185 else: -> 2186 ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args) 2187 ~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in _get_ufunc_and_otypes(self, func, args) 2145 inputs = [arg.flat[0] for arg in args] -> 2146 outputs = func(*inputs) 2147 ~\Anaconda3\lib\site-packages\matplotlib\dates.py in _to_ordinalf(dt) 225 --> 226 base = float(dt.toordinal()) 227 AttributeError: 'numpy.str_' object has no attribute 'toordinal' The above exception was the direct cause of the following exception: ConversionError Traceback (most recent call last) <ipython-input-11-21219a718bff> in <module> 38 plt.subplot(4,1,3) #MACD 39 plt.fill_between(date, df['macdhist'], alpha=0.5, label='MACD_hist') ---> 40 plt.hlines(0, start, end, 'gray', linestyle='dashed') 41 plt.legend() 42 ~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in hlines(y, xmin, xmax, colors, linestyles, label, data, **kwargs) 2664 y, xmin, xmax, colors=colors, linestyles=linestyles, 2665 label=label, **({"data": data} if data is not None else {}), -> 2666 **kwargs) 2667 2668 ~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs) 1599 def inner(ax, *args, data=None, **kwargs): 1600 if data is None: -> 1601 return func(ax, *map(sanitize_sequence, args), **kwargs) 1602 1603 bound = new_sig.bind(ax, *args, **kwargs) ~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in hlines(self, y, xmin, xmax, colors, linestyles, label, **kwargs) 1098 self._process_unit_info([xmin, xmax], y, kwargs=kwargs) 1099 y = self.convert_yunits(y) -> 1100 xmin = self.convert_xunits(xmin) 1101 xmax = self.convert_xunits(xmax) 1102 ~\Anaconda3\lib\site-packages\matplotlib\artist.py in convert_xunits(self, x) 178 if ax is None or ax.xaxis is None: 179 return x --> 180 return ax.xaxis.convert_units(x) 181 182 def convert_yunits(self, y): ~\Anaconda3\lib\site-packages\matplotlib\axis.py in convert_units(self, x) 1551 except Exception as e: 1552 raise munits.ConversionError('Failed to convert value(s) to axis ' -> 1553 f'units: {x!r}') from e 1554 return ret 1555 ConversionError: Failed to convert value(s) to axis units: '2019-11-01'

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

エラーが出たらまずはそのままググることです。さっそくTeratailの以前のQAがヒットしました
https://teratail.com/questions/218687

plotする時にx軸が日付型を用いているのにstart, endが文字列だからエラーとなっています。

のでdatetimeを用いて例えば下記のように
またspan02の定義が

Python

1df['RSI'] = ta.RSI(close, timeperiod=span02)

の後になっていてここでエラーが出ます。そのため定義を前にしました。
で下記

Python

1import pandas as pd 2import numpy as np 3import talib as ta 4from pandas_datareader import data 5import matplotlib.pyplot as plt 6%matplotlib inline 7from datetime import datetime 8 9start = '2019-11-01' 10end = '2020-11-01' 11df = data.DataReader('^N225', 'yahoo', start, end) 12 13span01 = 5 14span02 = 25 15span03 = 50 16 17date = df.index 18close = df['Adj Close'] 19df['macd'], df['macdsignal'], df['macdhist'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) 20df['RSI'] = ta.RSI(close, timeperiod=span02) 21 22 23 24df['mov01'] = close.rolling(window=span01).mean() 25df['mov02'] = close.rolling(window=span02).mean() 26df['mov03'] = close.rolling(window=span03).mean() 27 28plt.figure(figsize=(30,10)) 29plt.subplot(4,1,1) #移動平均 30 31plt.plot(date,close,label='Close') 32plt.plot(date, df['mov01'],label='mov01') 33plt.plot(date, df['mov02'],label='mov02') 34plt.plot(date, df['mov03'],label='mov03') 35plt.legend() 36 37plt.subplot(4,1,2) #出来高 38plt.bar(date, df['Volume'], label='Volume') 39plt.legend() 40 41 42plt.subplot(4,1,3) #MACD 43plt.fill_between(date, df['macdhist'], alpha=0.5, label='MACD_hist') 44plt.hlines(0, datetime.strptime(start, '%Y-%m-%d'), datetime.strptime(end, '%Y-%m-%d'), 'gray', linestyle='dashed') 45plt.legend() 46 47plt.subplot(4,1,4) #RSI 48plt.plot(date, df['RSI'], label='RSI') 49plt.ylim(0,100) 50plt.hlines([30,50,70], datetime.strptime(start, '%Y-%m-%d'), datetime.strptime(end, '%Y-%m-%d'), 'gray', linestyles='dashed') 51plt.legend()

投稿2020/11/07 06:21

aokikenichi

総合スコア2218

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

o-fk

2020/11/07 06:34

ありがとうございます! 定義の順序がそもそもおかしいことにも気づいておりませんでした((^^;)) 無事に出力もされました。ありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問