주식공부/파이썬 주식

파이썬으로 볼린저밴드를 만들어보기(feat. chatGPT)

일찍자요 2022. 12. 13. 21:27
반응형

GPT의 기능이 상상이상으로 많아서 보조지표를 코드로 만들어달라고 부탁을 해보았습니다.

 

make the python code to analysis bollinger band of KOSPI
KOSPI 볼린저밴드 분석하기위한 코드를 만들어줘.
 

To calculate the Bollinger Bands for the KOSPI index in Python, you will first need to obtain the historical data for the index. You can then use this data to calculate the moving average and standard deviation, which are used to plot the Bollinger Bands. Here is an example of how you can do this:

 

KOSPI 과거 데이터가 있어야하고 이동평균선과 표준편차를 이용해서 만들어진다는 얘기입니다.

 

그리고는 아래와 같이 코드를 짜주게 됩니다.

# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Load the historical data for the KOSPI index
# Replace this with your own data
kospi_data = pd.read_csv("kospi_data.csv")

# Calculate the 20-day moving average
kospi_data["ma20"] = kospi_data["Close"].rolling(20).mean()

# Calculate the 20-day standard deviation
kospi_data["std20"] = kospi_data["Close"].rolling(20).std()

# Calculate the upper and lower Bollinger Bands
kospi_data["upper"] = kospi_data["ma20"] + 2 * kospi_data["std20"]
kospi_data["lower"] = kospi_data["ma20"] - 2 * kospi_data["std20"]

# Plot the Bollinger Bands
plt.plot(kospi_data["Close"], label="Close")
plt.plot(kospi_data["ma20"], label="MA20")
plt.plot(kospi_data["upper"], label="Upper")
plt.plot(kospi_data["lower"], label="Lower")
plt.legend()
plt.show()

 

 

여기에서 코스피 데이터를 받아와야 하는데 그것 까진 제시를 안해줘서,

조금만 수정해보겠습니다.

 

finance datareader를 불러오고,

import FinanceDataReader as fdr

 

kospi_data를 바로 읽어주도록 합니다. 2010년 이후 데이터를 보도록 기준을 잡아보았습니다.

kospi_data = fdr.DataReader('KS11', '2010') # 특정 기간동안의 데이터를 보려면 기간을 적어준다.

 

수정된 코드는 아래와 같고, 20이평선은 따로 그리지 않고 종가만 나타내기로 하며, 종가는 검은색으로 표시하도록 수정해주었습니다.

# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import FinanceDataReader as fdr

# Load the historical data for the KOSPI index
# Replace this with your own data
# kospi_data = pd.read_csv("kospi_data.csv")
kospi_data = fdr.DataReader('KS11', '2010') # 특정 기간동안의 데이터를 보려면 기간을 적어준다.

# Calculate the 20-day moving average
kospi_data["ma20"] = kospi_data["Close"].rolling(20).mean()

# Calculate the 20-day standard deviation
kospi_data["std20"] = kospi_data["Close"].rolling(20).std()

# Calculate the upper and lower Bollinger Bands
kospi_data["upper"] = kospi_data["ma20"] + 2 * kospi_data["std20"]
kospi_data["lower"] = kospi_data["ma20"] - 2 * kospi_data["std20"]

# Plot the Bollinger Bands
plt.plot(kospi_data["Close"], label="Close", color = 'black')
# plt.plot(kospi_data["ma20"], label="MA20")
plt.plot(kospi_data["upper"], label="Upper")
plt.plot(kospi_data["lower"], label="Lower")
plt.legend()
plt.show()

 

 

그리고 실행해보면, 이렇게 볼린저밴드가 그려집니다.

 

 

 

이제는 코딩도 컴퓨터가 짜주는 시대가 되어버렸습니다....

 

반응형