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

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

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

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

Q&A

2回答

766閲覧

コードhttps://teratail.com/contact/inputエラーにより株価データが取得できない

noriyuki0413

総合スコア0

Python

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

0グッド

0クリップ

投稿2020/11/11 11:28

前提・実現したいこと

株価データを取得したいのですが、以下よりコードを取得しましたが、エラーが発生
https://non-dimension.com/kabuka-scraping/

python_code

from bs4 import BeautifulSoup
import pandas as pd
import requests
from datetime import datetime

def get_dfs(stock_number):
dfs = []
year = [2018,2019] #2017〜2019年までの株価データを取得
for y in year:
try:
print(y)
url = 'https://kabuoji3.com/stock/{}/{}/'.format(stock_number,y)
soup = BeautifulSoup(requests.get(url).content,'html.parser')
tag_tr = soup.find_all('tr')
head = [h.text for h in tag_tr[0].find_all('th')]
data = []
for i in range(1,len(tag_tr)):
data.append([d.text for d in tag_tr[i].find_all('td')])
df = pd.DataFrame(data, columns = head)

col = ['始値','高値','安値','終値','出来高','終値調整'] for c in col: df[c] = df[c].astype(float) df['日付'] = [datetime.strptime(i,'%Y-%m-%d') for i in df['日付']] dfs.append(df) except IndexError: print('No data') return dfs

def concatenate(dfs):
data = pd.concat(dfs,axis=0)
data = data.reset_index(drop=True)
col = ['始値','高値','安値','終値','出来高','終値調整']
for c in col:
data[c] = data[c].astype(float)
return data

#作成したコードリストを読み込む
code_list= pd.read_excel('C:/Users/USER/Desktop/code_list.xlsx',sheet_name="code_list",index_col=0)

#複数のデータフレームをcsvで保存
for i in range(len(code_list)):
k = code_list.loc[i,'code']
v = code_list.loc[i,'name']
print(k,v)
dfs = get_dfs(k)
data = concatenate(dfs)
data.to_csv('{}-{}.csv'.format(k,v))

発生している問題・エラーメッセージ

KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

During handling of the above exception, another exception occurred:

KeyError Traceback (most recent call last)
<ipython-input-14-f6fe2079100e> in <module>
41 #複数のデータフレームをcsvで保存
42 for i in range(len(code_list)):
---> 43 k = code_list.loc[i,'code']
44 v = code_list.loc[i,'name']
45 print(k,v)

~\anaconda3\lib\site-packages\pandas\core\indexing.py in getitem(self, key)
1759 except (KeyError, IndexError, AttributeError):
1760 pass
-> 1761 return self._getitem_tuple(key)
1762 else:
1763 # we by definition only have the 0th axis

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_tuple(self, tup)
1269 def _getitem_tuple(self, tup: Tuple):
1270 try:
-> 1271 return self._getitem_lowerdim(tup)
1272 except IndexingError:
1273 pass

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_lowerdim(self, tup)
1386 for i, key in enumerate(tup):
1387 if is_label_like(key) or isinstance(key, tuple):
-> 1388 section = self._getitem_axis(key, axis=i)
1389
1390 # we have yielded a scalar ?

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis)
1962 # fall thru to straight lookup
1963 self._validate_key(key, axis)
-> 1964 return self._get_label(key, axis=axis)
1965
1966

~\anaconda3\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis)
622 raise IndexingError("no slices here, handle elsewhere")
623
--> 624 return self.obj._xs(label, axis=axis)
625
626 def _get_loc(self, key: int, axis: int):

~\anaconda3\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level)
3535 loc, new_index = self.index.get_loc_level(key, drop_level=drop_level)
3536 else:
-> 3537 loc = self.index.get_loc(key)
3538
3539 if isinstance(loc, np.ndarray):

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2646 return self._engine.get_loc(key)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2650 if indexer.ndim > 1 or indexer.size > 1:

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

試したこと

以下の株価を取得したい。

code_list.xlsx
code name
2424 ブラス
2820 やまみ?
2970 グッドライフC
3134 Hamee
3172 ティーライフ
3180 ビューティガレージ
3189 ANAP

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

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

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

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

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

y_waiwai

2020/11/11 11:41

このままではコードが読めないので、質問を編集し、<code>ボタンを押し、出てくる’’’の枠の中にコードを貼り付けてください
guest

回答2

0

code_list= pd.read_excel('code_list.xlsx',sheet_name="code_list",index_col=0) code_list= pd.read_excel('code_list.xlsx',sheet_name="code_list")にすれば良いです。

投稿2020/11/11 12:14

meg_

総合スコア10580

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

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

noriyuki0413

2020/11/14 12:10

code_listは以下の銘柄です。 code name 1301 極洋 1332 日本水産 1333 マルハニチロ 1352 ホウスイ 1375 雪国まいたけ 1376 カネコ種苗 1377 サカタのタネ 実際にはデータがあるのに以下のとおり、の結果エラーになります。 萎えてkます。。 1301 極洋 2018 No data 2019 No data --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-2-cde5d95fd82f> in <module> 45 print(k,v) 46 dfs = get_dfs(k) ---> 47 data = concatenate(dfs) 48 data.to_csv('C:/Users/USER/Desktop/{}-{}.csv'.format(k,v)) <ipython-input-2-cde5d95fd82f> in concatenate(dfs) 29 30 def concatenate(dfs): ---> 31 data = pd.concat(dfs,axis=0) 32 data = data.reset_index(drop=True) 33 col = ['始値','高値','安値','終値','出来高','終値調整'] ~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in concat(objs, axis, join, ignore_index, keys, levels, names, verify_integrity, sort, copy) 279 verify_integrity=verify_integrity, 280 copy=copy, --> 281 sort=sort, 282 ) 283 ~\anaconda3\lib\site-packages\pandas\core\reshape\concat.py in __init__(self, objs, axis, join, keys, levels, names, ignore_index, verify_integrity, copy, sort) 327 328 if len(objs) == 0: --> 329 raise ValueError("No objects to concatenate") 330 331 if keys is None: ValueError: No objects to concatenate
meg_

2020/11/14 12:47

> 実際にはデータがあるのに以下のとおり、の結果エラーになります。 "実際にはデータがあるのに"の部分が分かりませんが、データが取得できないものがエラーになっていると思われます。 dfsが空のリストだとエラーになるようですね。エラー回避処理を追加すれば良いでしょう。
guest

0

pandasのDataReaderだと、簡単に株価をとってきてくれます。
ローソクチャートもすぐに作れます。
試してみてはいかがでしょう。

brass = pdr.DataReader("{}.JP".format(2424), "stooq")
mpf.plot(brass, type='candle', style='yahoo', volume=True, mav=(3, 7, 15))

イメージ説明

投稿2020/11/11 11:49

technocore

総合スコア7225

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問