
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
필요한 열만 골라내는 식을 쓰는데요.
분명히 Date가 있어서 그걸 썼고, 자꾸 오류가 나서 복사해서 붙여넣기까지 했는데도 자꾸 오류가 나서, 그럼 그건 골라내지 말고 다른 거나 일단 골라서 보자는 심정으로 Date를 지워버렸더니 원하는 대로 나왔어요. 왜 그런걸까요?


작성한 코드 및 에러 메세지
df = fdr.DataReader('005930','2018')
df = df[['Close']]
df['ma'] = df.rolling(3).mean().shift(1)#rolling(3)은 3일간, shift(1)은 한 칸 아래로 내림
df['action'] = np.where(df['Close'] > df['ma'], 'buy', 'sell')
df['action_temp'] = df['action'].shift(1)#action 열과 action_temp 열의 내용이 다른 부분을 찾기 위한 사전작업
df.iloc[-1,-1] = 'sell'#마지막엔 팔아야 이익을 실현할 수 있기 때문이지
cond = (df['action'] == 'buy') & (df['action_temp'] =='sell')
cond1= (df['action'] == 'sell') & (df['action_temp'] =='buy')
df['real_buy'] = np.where(cond,'buy', np.where(cond1,'sell',''))
df = df[['Close','ma','real_buy']]#왜 'Date'를 쓰면 오류가 나는 걸까?
df_buy = df[cond].reset_index()
df_buy.columns = ['날짜', '종가(buy)', '3일 이평값', '액션']
df_sell = df[cond1].reset_index()#.reset_index()가 없을 때는 한 줄은 buy, ,한 줄은 sell로 번갈아 나왔는데, 이걸 붙이니까 반쪽에만 있던 빈 줄이 없어진다.
df_sell.columns = ['날짜', '종가(sell)', '3일 이평값', '액션']
print(df_buy) #이렇게 하니까 멋없게 나오는구만.
df_sell#이렇게 하니까 예쁘게 나오는구만.
df_result = pd.concat([df_buy,df_sell],axis=1)#axis=1 때문에 두 표가 옆으로 붙음
df_result
날짜 종가(buy) 3일 이평값 액션
0 2018-01-05 52120 51240.000000 buy
1 2018-01-15 48540 48426.666667 buy
2 2018-01-23 49160 49153.333333 buy
3 2018-02-12 45720 45500.000000 buy
4 2018-02-23 47220 47146.666667 buy
.. ... ... ... ...
196 2023-04-21 65700 65466.666667 buy
197 2023-04-27 64600 64300.000000 buy
198 2023-05-08 65900 65400.000000 buy
199 2023-05-15 64500 64300.000000 buy
200 2023-05-26 70300 68566.666667 buy
[201 rows x 4 columns]
날짜 종가(buy) 3일 이평값 액션 날짜 종가(sell) 3일 이평값 액션
0 2018-01-05 52120 51240.000000 buy 2018-01-09 50400.0 51740.000000 sell
1 2018-01-15 48540 48426.666667 buy 2018-01-19 49320.0 49840.000000 sell
2 2018-01-23 49160 49153.333333 buy 2018-01-30 49800.0 50753.333333 sell
3 2018-02-12 45720 45500.000000 buy 2018-02-20 47400.0 48306.666667 sell
4 2018-02-23 47220 47146.666667 buy 2018-02-28 47060.0 47326.666667 sell
... ... ... ... ... ... ... ... ...
196 2023-04-21 65700 65466.666667 buy 2023-04-24 65200.0 65500.000000 sell
197 2023-04-27 64600 64300.000000 buy 2023-05-04 65100.0 65533.333333 sell
198 2023-05-08 65900 65400.000000 buy 2023-05-09 65300.0 65466.666667 sell
199 2023-05-15 64500 64300.000000 buy NaT NaN NaN NaN
200 2023-05-26 70300 68566.666667 buy NaT NaN NaN NaN
201 rows × 8 columns
