인프런 커뮤니티 질문&답변

dkdlel444님의 프로필 이미지
dkdlel444

작성한 질문수

파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part1

2.6 reindex 관련 예제 질문

해결된 질문

작성

·

445

0

1.PNG아래의 에러가 발생했을 때 어떻게 진행해야 할지 모르겠습니다.

df1과 df2의 실행이 안됩니다.

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\pandas\core\computation\scope.py:198, in Scope.resolve(self, key, is_local)
    197 if self.has_resolvers:
--> 198     return self.resolvers[key]
    200 # if we're here that means that we have no locals and we also have
    201 # no resolvers

File ~\anaconda3\Lib\collections\__init__.py:1004, in ChainMap.__getitem__(self, key)
   1003         pass
-> 1004 return self.__missing__(key)

File ~\anaconda3\Lib\collections\__init__.py:996, in ChainMap.__missing__(self, key)
    995 def __missing__(self, key):
--> 996     raise KeyError(key)

KeyError: 'Timestamp'

During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\pandas\core\computation\scope.py:209, in Scope.resolve(self, key, is_local)
    205 try:
    206     # last ditch effort we look in temporaries
    207     # these are created when parsing indexing expressions
    208     # e.g., df[df > 0]
--> 209     return self.temps[key]
    210 except KeyError as err:

KeyError: 'Timestamp'

The above exception was the direct cause of the following exception:

UndefinedVariableError                    Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:666, in BaseExprVisitor.visit_Call(self, node, side, **kwargs)
    665 try:
--> 666     res = self.visit(node.func)
    667 except UndefinedVariableError:
    668     # Check if this is a supported function name

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:549, in BaseExprVisitor.visit_Name(self, node, **kwargs)
    548 def visit_Name(self, node, **kwargs):
--> 549     return self.term_type(node.id, self.env, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\ops.py:85, in Term.__init__(self, name, env, side, encoding)
     84 self.is_local = tname.startswith(LOCAL_TAG) or tname in DEFAULT_GLOBALS
---> 85 self._value = self._resolve_name()
     86 self.encoding = encoding

File ~\anaconda3\Lib\site-packages\pandas\core\computation\ops.py:109, in Term._resolve_name(self)
    107     is_local = False
--> 109 res = self.env.resolve(local_name, is_local=is_local)
    110 self.update(res)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\scope.py:211, in Scope.resolve(self, key, is_local)
    210 except KeyError as err:
--> 211     raise UndefinedVariableError(key, is_local) from err

UndefinedVariableError: name 'Timestamp' is not defined

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[2], line 2
      1 # 삼성전자
----> 2 df1 = fdr.DataReader("005930", '2018-01-02', '2018-10-30')
      4 # KODEX 200 (ETF)
      5 df2 = fdr.DataReader("069500", '2018-01-03', '2018-10-30')

File ~\anaconda3\Lib\site-packages\FinanceDataReader\data.py:19, in DataReader(symbol, start, end, exchange, kind)
     16 start, end = _validate_dates(start, end)
     17 if (symbol.isdigit() and len(symbol)==6 and exchange==None) or \
     18    (symbol.isdigit() and exchange and exchange.upper() in ['KRX', '한국거래소']):
---> 19     return NaverDailyReader(symbol, start, end, exchange, kind).read()
     21 if (symbol.isdigit() and exchange and exchange.upper() in ['KRX-DELISTING']):
     22     return KrxDelistingReader(symbol, start, end, exchange, kind).read()

File ~\anaconda3\Lib\site-packages\FinanceDataReader\naver\data.py:29, in NaverDailyReader.read(self)
     26 df.sort_index(inplace=True)
     27 df['Change'] = df['Close'].pct_change()
---> 29 return df.query('index>=%r and index<=%r' % (self.start, self.end))

File ~\anaconda3\Lib\site-packages\pandas\util\_decorators.py:331, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    325 if len(args) > num_allow_args:
    326     warnings.warn(
    327         msg.format(arguments=_format_argument_list(allow_args)),
    328         FutureWarning,
    329         stacklevel=find_stack_level(),
    330     )
--> 331 return func(*args, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\frame.py:4474, in DataFrame.query(self, expr, inplace, **kwargs)
   4472 kwargs["level"] = kwargs.pop("level", 0) + 2
   4473 kwargs["target"] = None
-> 4474 res = self.eval(expr, **kwargs)
   4476 try:
   4477     result = self.loc[res]

File ~\anaconda3\Lib\site-packages\pandas\util\_decorators.py:331, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    325 if len(args) > num_allow_args:
    326     warnings.warn(
    327         msg.format(arguments=_format_argument_list(allow_args)),
    328         FutureWarning,
    329         stacklevel=find_stack_level(),
    330     )
--> 331 return func(*args, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\frame.py:4612, in DataFrame.eval(self, expr, inplace, **kwargs)
   4609     kwargs["target"] = self
   4610 kwargs["resolvers"] = tuple(kwargs.get("resolvers", ())) + resolvers
-> 4612 return _eval(expr, inplace=inplace, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\eval.py:353, in eval(expr, parser, engine, truediv, local_dict, global_dict, resolvers, level, target, inplace)
    344 # get our (possibly passed-in) scope
    345 env = ensure_scope(
    346     level + 1,
    347     global_dict=global_dict,
   (...)
    350     target=target,
    351 )
--> 353 parsed_expr = Expr(expr, engine=engine, parser=parser, env=env)
    355 # construct the engine and evaluate the parsed expression
    356 eng = ENGINES[engine]

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:813, in Expr.__init__(self, expr, engine, parser, env, level)
    811 self.parser = parser
    812 self._visitor = PARSERS[parser](self.env, self.engine, self.parser)
--> 813 self.terms = self.parse()

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:832, in Expr.parse(self)
    828 def parse(self):
    829     """
    830     Parse an expression.
    831     """
--> 832     return self._visitor.visit(self.expr)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:421, in BaseExprVisitor.visit_Module(self, node, **kwargs)
    419     raise SyntaxError("only a single expression is allowed")
    420 expr = node.body[0]
--> 421 return self.visit(expr, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:424, in BaseExprVisitor.visit_Expr(self, node, **kwargs)
    423 def visit_Expr(self, node, **kwargs):
--> 424     return self.visit(node.value, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:750, in BaseExprVisitor.visit_BoolOp(self, node, **kwargs)
    747     return self._maybe_evaluate_binop(op, node.op, lhs, rhs)
    749 operands = node.values
--> 750 return reduce(visitor, operands)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:743, in BaseExprVisitor.visit_BoolOp.<locals>.visitor(x, y)
    742 def visitor(x, y):
--> 743     lhs = self._try_visit_binop(x)
    744     rhs = self._try_visit_binop(y)
    746     op, op_class, lhs, rhs = self._maybe_transform_eq_ne(node, lhs, rhs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:739, in BaseExprVisitor._try_visit_binop(self, bop)
    737 if isinstance(bop, (Op, Term)):
    738     return bop
--> 739 return self.visit(bop)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:723, in BaseExprVisitor.visit_Compare(self, node, **kwargs)
    721     op = self.translate_In(ops[0])
    722     binop = ast.BinOp(op=op, left=node.left, right=comps[0])
--> 723     return self.visit(binop)
    725 # recursive case: we have a chained comparison, a CMP b CMP c, etc.
    726 left = node.left

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:536, in BaseExprVisitor.visit_BinOp(self, node, **kwargs)
    535 def visit_BinOp(self, node, **kwargs):
--> 536     op, op_class, left, right = self._maybe_transform_eq_ne(node)
    537     left, right = self._maybe_downcast_constants(left, right)
    538     return self._maybe_evaluate_binop(op, op_class, left, right)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:458, in BaseExprVisitor._maybe_transform_eq_ne(self, node, left, right)
    456     left = self.visit(node.left, side="left")
    457 if right is None:
--> 458     right = self.visit(node.right, side="right")
    459 op, op_class, left, right = self._rewrite_membership_op(node, left, right)
    460 return op, op_class, left, right

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:415, in BaseExprVisitor.visit(self, node, **kwargs)
    413 method = "visit_" + type(node).__name__
    414 visitor = getattr(self, method)
--> 415 return visitor(node, **kwargs)

File ~\anaconda3\Lib\site-packages\pandas\core\computation\expr.py:670, in BaseExprVisitor.visit_Call(self, node, side, **kwargs)
    667 except UndefinedVariableError:
    668     # Check if this is a supported function name
    669     try:
--> 670         res = FuncNode(node.func.id)
    671     except ValueError:
    672         # Raise original error
    673         raise

File ~\anaconda3\Lib\site-packages\pandas\core\computation\ops.py:614, in FuncNode.__init__(self, name)
    612 def __init__(self, name: str) -> None:
    613     if name not in MATHOPS:
--> 614         raise ValueError(f'"{name}" is not a supported function')
    615     self.name = name
    616     self.func = getattr(np, name)

ValueError: "Timestamp" is not a supported function

답변 1

0

dkdlel444님의 프로필 이미지
dkdlel444
질문자

[해결 완료 과정 기록]

 

최신버전 업데이트 하면 해결된다고 해서 검색 후 업데이트 방법 찾음

 

일단 아나콘다 삭제 후 다시 설치 함

 

강의자료 말고 새로운 파일 열어서 코드 작성함

 

!pip install pandas

 

입력하여 최신버전 업데이트함(23-08-30 기준 업데이트 전 pandas 1.5.3 version)

 

import pandas as pd

pd.__version__

 

로 확인하니 1.5.3 이었음

 

conda update --all

 

을 통해 라이브러리 업데이트 수행

Note: you may need to restart the kernel to use updated packages.
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/msys2/noarch/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/r/noarch/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/msys2/win-64/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/noarch/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/r/win-64/current_repodata.json HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): repo.anaconda.com:443
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/datashader-0.15.2-py311haa95532_0.tar.bz2 HTTP/1.1" 200 17851220
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/grpc-cpp-1.48.2-hf108199_0.conda HTTP/1.1" 200 24603538
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/libxslt-1.1.37-h2bbff1b_1.conda HTTP/1.1" 200 457852
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/botocore-1.29.76-py311haa95532_0.conda HTTP/1.1" 200 6662107
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/safetensors-0.3.2-py311h062c2fa_0.conda HTTP/1.1" 200 279828
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/qt-main-5.15.2-h6072711_9.conda HTTP/1.1" 200 62316326
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/multiprocess-0.70.14-py311haa95532_0.conda HTTP/1.1" 200 330150
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/huggingface_hub-0.15.1-py311haa95532_0.conda HTTP/1.1" 200 415874
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/scipy-1.11.1-py311hc1ccb85_0.conda HTTP/1.1" 200 21771686
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/spyder-kernels-2.4.4-py311haa95532_0.conda HTTP/1.1" 200 210615
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/conda-libmamba-solver-23.7.0-py311haa95532_0.conda HTTP/1.1" 200 92447
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/tokenizers-0.13.2-py311h49fca51_1.conda HTTP/1.1" 200 2953006
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/libxml2-2.10.4-h0ad7f3c_1.conda HTTP/1.1" 200 2976881
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/boost-cpp-1.82.0-h59b6b97_1.conda HTTP/1.1" 200 11797
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/ipython-8.12.2-py311haa95532_0.conda HTTP/1.1" 200 1507026
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/pytables-3.8.0-py311h4671533_3.conda HTTP/1.1" 200 2233335
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/pandas-2.0.3-py311hf62ec03_0.conda HTTP/1.1" 200 12530146
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/python-xxhash-2.0.2-py311h2bbff1b_1.conda HTTP/1.1" 200 22089
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/aiobotocore-2.5.0-py311haa95532_0.conda HTTP/1.1" 200 154739
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/s3fs-2023.4.0-py311haa95532_0.conda HTTP/1.1" 200 77605
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/platformdirs-3.10.0-py311haa95532_0.conda HTTP/1.1" 200 41274
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/openssl-1.1.1v-h2bbff1b_0.conda HTTP/1.1" 200 5773548
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/cryptography-39.0.1-py311h21b164f_0.conda HTTP/1.1" 200 1079730
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/noarch/responses-0.13.3-pyhd3eb1b0_0.conda HTTP/1.1" 200 25024
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/ipykernel-6.25.0-py311h746a85d_0.conda HTTP/1.1" 200 315883
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/pyarrow-11.0.0-py311h8a3a540_1.conda HTTP/1.1" 200 3171200
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/conda-content-trust-0.1.3-py311haa95532_0.conda HTTP/1.1" 200 99747
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/h5py-3.9.0-py311h4e0e482_0.conda HTTP/1.1" 200 1010811
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/mkl-2023.1.0-h6b88ed4_46357.conda HTTP/1.1" 200 163131907
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/noarch/python-tzdata-2023.3-pyhd3eb1b0_0.conda HTTP/1.1" 200 143832
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/krb5-1.20.1-h5b6d351_1.conda HTTP/1.1" 200 805284
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/arrow-cpp-11.0.0-h2c9b28c_2.conda HTTP/1.1" 200 7648722
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/qt-webengine-5.15.9-h5bd16bc_7.conda HTTP/1.1" 200 60963283
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/transformers-4.32.1-py311haa95532_0.conda HTTP/1.1" 200 9083543
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/xxhash-0.8.0-h2bbff1b_3.conda HTTP/1.1" 200 89482
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/hdf5-1.12.1-h51c971a_3.conda HTTP/1.1" 200 12486857
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/datasets-2.12.0-py311haa95532_0.conda HTTP/1.1" 200 899103
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/conda-23.7.3-py311haa95532_0.conda HTTP/1.1" 200 1403925
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/libboost-1.82.0-hae598e9_1.conda HTTP/1.1" 200 23697549
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/libpq-12.15-h906ac69_0.conda HTTP/1.1" 200 3278278
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/fsspec-2023.4.0-py311haa95532_0.conda HTTP/1.1" 200 326599
DEBUG:urllib3.connectionpool:https://repo.anaconda.com:443 "GET /pkgs/main/win-64/conda-build-3.26.1-py311haa95532_0.conda HTTP/1.1" 200 838755

 

마지막 부분에 이런 에러가 발생하긴 했지만 최신버전 업데이트 확인해서 그냥 넘어감

 

import pandas as pd

pd.__version__

'2.0.3'


버전이 2.0.3 으로 pandas 업데이트 확인함

 

import numpy as np

np.__version__

'1.24.3'

 

!pip install finance-datareader

import FinanceDataReader as fdr

 

SAM = fdr.DataReader("005930")

SAM


image

image

 

강의자료대로 코드 입력 후 실행하니 잘 나오는 것을 확인함

DeepingSauce님의 프로필 이미지
DeepingSauce
지식공유자

공유 감사드립니다: ) 문제 해결과정을 기록으로 많이 남겨두면 빠르게 성장하실거에요 ㅎㅎ

dkdlel444님의 프로필 이미지
dkdlel444

작성한 질문수

질문하기