묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part1
강의자료
선생님이 사용하시는 강의자료 따로 다운 받을 수 있나요?
-
해결됨파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part1
2.6 reindex 관련 예제 질문
아래의 에러가 발생했을 때 어떻게 진행해야 할지 모르겠습니다.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
-
미해결퀀트 투자를 위한 파이썬 트레이딩룸 만들기 - Part 1
nbextension 없이는 안되나요?
구글링 해보니 stackoverflow에 4일전에 정확히 동일한 질문이 올라왔는데 답이 없는 상태인걸로 봐서 jupyter notebook 최신버전에서 생기는 문제 같기도 합니다.정보가 없어 해결이 어렵네요.https://stackoverflow.com/questions/76893872/modulenotfounderror-no-module-named-notebook-base-when-installing-nbextension
-
미해결퀀트 투자를 위한 파이썬 트레이딩룸 만들기 - Part 2
pt3은 언제쯤 나올까요?
정말 흥미롭게 Pt1부터 잘 수강하고 있습니다.파트3에 대한 계획은 있으신 것 같은데 언제쯤일지 궁금합니다!
-
미해결파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part1
my_data
my_data 자료를 최신 자료 기준으로 실습 할 수 있도록 2020,2021,2022년도 분도 올려주시면 좋겠습니다.
-
미해결평생 써먹는 데이터 기반 투자법 with 파이썬 퀀트 투자
리밸런싱에서 주기와 가중치 변경시 오류 현상
안녕하세요. 이전 맛집지도 프로젝트부터 이번 강의까지 재미있게 수강하고 있습니다. 다음 강좌도 재미있는 콘텐츠 내주시면 수강하려고 합니다.다름이 아니라, [2-5. 리밸런싱 기법]에서 강의에서는 weight를 1:1로 설정하고, Month 단위 리밸런싱만 다루는데요. 리밸런싱 주기를 quarter 또는 year로 하고 가중치를 달리 먹이면 오류가 발생합니다.closeDateSet의 날짜와 rebalancingDate의 날짜가 일치하지 않기 때문인 것 같은데요. 나름대로 열심히 손대봐도 답을 못찾아서 도움을 부탁드립니다. weight를 어떻게 집어 넣는지 다뤄주시면 좋을 것 같습니다. 감사합니다.# 데이터 로드 stockETF = getCloseData("SPY", "2002", "2022-6-17") # 주식 ETF bondETF = getCloseData("IEF", "2002", "2022-6-17") # 채권 ETF # kodex200 = 069500 # kodex10Bond = 152380 # S&P500 = SPY # 미국 7-10 국채 = IEF closeDataSet = pd.concat([stockETF, bondETF], axis=1) closeDataSet.columns = ['stockETF', 'bondETF'] closeDataSet.dropna(inplace=True) closeDataSet # 종목의 상장일을 기준으로 리밸런싱 날짜 선별 # rebalancingDate = getRebalancingDate(closeDataSet) rebalancingDate = getRebalancingDate(closeDataSet, "quarter") rebalancingDate # 리밸런싱 날짜에 맞춰서 가중치 설정 weightSet1 = pd.DataFrame({ 'stockETF': [0.7] * len(rebalancingDate), 'bondETF': [0.3] * len(rebalancingDate) }, index=rebalancingDate) # 모든 리밸런싱 날짜에 대한 가중치 지정 rebalPortfolioDayReturn, rebalPortfolioCumulativeReturn = getRebalancingPortfolioResult(closeDataSet, weightDf=weightSet1)
-
미해결퀀트 투자를 위한 주식 자동매매 봇 만들기 Part 1
파이참 가상환경 설정도 해주어야 되는지
궁금합니다.
-
미해결퀀트 투자를 위한 주식 자동매매 봇 만들기 Part 1
파이썬 예제 코드 실습 에러
예제 코드를 파이참을 실행해서 어느 프로그램 경로에다가 어떤식으로 연결해야 실행이 되는지 잘 모르겠습니다. 현재 예제 코드가 실행이 잘 안되서요
-
미해결금융데이터 분석을 위한 판다스 활용법
DataFrame 강의 중 About NaN 질문입니다.
안녕하세요, 수업 잘 듣고 있습니다. 감사합니다.강의 중 DataFrame 값 중 NaN인 값의 날짜를 추출하는 방법이 있었습니다. 이 부분이 잘 이해가 안가서 질문을 드립니다.df_samsung_close.isna() 를 하게 되면, 삼성전자의 종가값이 있는 날은 False, 없는 날은 True이고 인덱스가 날짜인 데이터프레임이 조회됩니다. 따라서, df_samsung_close.isna().values를 하면 True와 False로 이루어진 numpy array가 출력됩니다. 이때 선생님께서는 df_samsung_close[df_samsung_close.isna().values].index를 이용해서 답을 찾으셨는데,일단 데이터프레임[np array]가 의미하는 바를 모르겠습니다. 데이터프레임[np.array(true, false,...)] 했더니 true인 값만이 조회가 되는 syntax가 잘 이해가 가지 않아서요.설명해주실 수 있나요?
-
미해결모두를 위한 ChatGPT Part 3 - ChatGPT로 퀀트 투자 전략 만들기
FinanceDataReader 관련 문의드립니다
FinanceDataReader로 코스피, 코스닥 데이터를 불러오면 강의에서는 컬럼이 10개인데 제가 불러들이니까 컬럼 17개에 symbol, sector, industry가 안나오고 다른 카테고리들이 나오는데 FinanceDataReader가 업데이트가 되어서 그런건가요?
-
미해결평생 써먹는 데이터 기반 투자법 with 파이썬 퀀트 투자
리밸런싱 포트폴리오 구현 원리 질문있습니다.
안녕하세요.리밸런싱 포트폴리오 구현 원리에서 리밸런싱 일자(노란색) 비중을 리밸런싱 기간이 아닌 모든 행에 곱해주면 곱하는 날 모두 리밸런싱이 적용되는 것이 아닌가요? 리밸런싱 일자에만 비중을 곱해주고 나머지는 그대로 누적수익률을 구해야하는 것이 아닌지 이해가 잘 가지 않아서 질문드립니다.
-
미해결퀀트 투자를 위한 파이썬 트레이딩룸 만들기 - Part 2
df_etf.Xlsx 파일 최신 날짜로 업데이트
엑셀 파일 자료중에서 df_etf.Xlsx 파일 최신 날짜로 업데이트 하려면 어떻게 하나요?
-
미해결비트코인 알고리즘 트레이딩 봇 개발
바이낸스 오픈 API 깃허브 링크
안녕하세요! 강의 너무 잘 보고 있습니다.혹시 바이낸스 오픈 API를 제공하는 깃허브링크로 갔는데 삭제된 링크 인것 같습니다. https://github.com/Binance-docs/Binance_Futures_python다른 깃허브 페이지로 옮긴걸까요?
-
미해결파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part1
드랍박스 경로 다시 공유해주실수있나요?
3.1 EDA 소개강의 초반에 나오는 드랍박스 경로 막힌것 같은데다시 공유 가능한가요?
-
미해결퀀트 투자를 위한 파이썬 트레이딩룸 만들기 - Part 2
spyder에서 실행시 dash.html이 없다는 에러가 나옵니다.
pip install 로 dash module 설치하고, 스파이더로 실행을 해 보는데, 한번 실행 되더니 그 다음 부터는 되지가 않습니다. pip list 해 보면 dash 모듈이 설치되어 있는 것이 보입니다.어디가 에러일까요?
-
미해결퀀트 투자를 위한 파이썬 트레이딩룸 만들기 - Part 2
sell in may heatmap
sell in may... 가 맞는지 알아 보기 위해서 heatmap 그릴 때, 모든 ETF의 연도별 월별 수익률 평균을 구해 보는 것은 의미가 있을까요? 이렇게 구해보면 sell in may... 라는 말은 맞이 않는 것 같습니다. 이렇게 하는 것도 의미가 있을까요?import pandas as pdimport numpy as npimport plotly.graph_objects as godf = pd.read_excel('df_etf.xlsx', index_col = 0)df_copy = df.copy()# KODEX ETF data 추출condition_kodex = [df_copy.columns[i] for i in range(df_copy.shape[1]) if 'KODEX' in df_copy.columns[i]] # list comprehensiondf_copy_kodex = df_copy.loc[:, condition_kodex]df_copy_kodex['YEAR'] = df_copy_kodex.index.yeardf_copy_kodex['MONTH'] = df_copy_kodex.index.month# 년도별 월별 모든 ETF 수익률 평균 YEAR = 2012 # ETF data 기간 : 2012 ~ 2022empty_df = pd.DataFrame()while YEAR < 2023 : YEAR = YEAR df_copy_kodex_yr = df_copy_kodex[df_copy_kodex['YEAR'] == YEAR] df_copy_gr = df_copy_kodex_yr.groupby('MONTH') df_sell_in_may = df_copy_gr.mean() df_month_return = np.round((df_sell_in_may.mean(axis = 1).pct_change(periods = 1))*100, 2) empty_df[YEAR] = df_month_return YEAR = (YEAR + 1)trace = go.Heatmap(x = empty_df.columns, y = empty_df.index, z = empty_df)fig = go.Figure(data = trace)fig.show()
-
미해결파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part2
fdr.DataReader 오류
ValueError: "Timestamp" is not a supported functionfinancedatareader를 import 하면 되는데, 실제로 데이터를 불러오면 저런 에러가 뜹니다.예 : df1 = fdr.DataReader("005930", '2018-01-02', '2018-10-30') 인터넷을 뒤져도 해결책이 잘 나오지 않는데 도움이 필요합니다버전은 아래와 같습니다finance-datareader==0.9.31
-
미해결비트코인 알고리즘 트레이딩 봇 개발
데이터 수집하기 오류 질문
8분 22초 print(type(webpage)) run하면 아무 결과값이 안뜹니다14분 50초 run 눌러도실행이 안되고 오류가 납니다. File "C:\Users\kimminsoo\AppData\Local\Temp\ipykernel_6404\2059768320.py", line 31 $ print(df_temp_data.head(5)) ^ SyntaxError: invalid syntax 이런 오류메시지가 뜹니다 뭐가 문제인가요?
-
해결됨파이썬(Python)으로 데이터 기반 주식 퀀트 투자하기 Part2
fdr.DataReader 오류
ValueError: "Timestamp" is not a supported functionfinancedatareader를 import 하면 되는데, 실제로 데이터를 불러오면 저런 에러가 뜹니다.예 : df1 = fdr.DataReader("005930", '2018-01-02', '2018-10-30') 인터넷을 뒤져도 해결책이 잘 나오지 않는데 도움이 필요합니다
-
미해결평생 써먹는 데이터 기반 투자법 with 파이썬 퀀트 투자
FAA 전략에서 상관성
안녕하세요 강좌를 듣던중 궁금증이 생겨서 글 남깁니다.FAA 전략을 보면 상관성이 낮은 종목들의 순위를 높게 주려는거 같은데요.해당 수치를 계산할때 합산을 해버리면 '상관성이 낮다'의 의미는 아닌거 같습니다.abs나 **2 해서 합산을 하고 그 수치가 작은 것이 자산간의 상관관계가 낮은게 아닌가 생각됩니다.예를 들어 1과 -1 은 둘다 상관관계는 높습니다.