본문 바로가기
코딩 공부/python

ChatGPT와 함께 커버드 콜 전략 자동실행 알고리즘 짜기 (5)

by Camel_coding_food 2023. 2. 13.
반응형

궁금한 코드를 찾아보면 제야의 고수가 많더군요.

 

저번 게시물에서 예고한대로

커버드 콜 전략 원리를 일단 알아보겠습니다.

 


시사저널e에서 가져온 이미지입니다.

 

간단히 말하면 커버드콜 전략은 기초자산을 매수하고,

콜옵션을 매도하는 것입니다.

 

 

콜옵션이란 기초상품을 매수할 수 있는 권리를 말합니다.

 

 

콜옵션을 매도한다는 것은,

콜옵션 매수자에게 특정 가격에 매수할 권리를 주는 것입니다.

 

예를 들어, 삼성전자 주가가 6만원일때 65000원에 살 권리를 사고 판다는 것입니다.

그렇다면  왜 콜옵션 매수자는 현재가 보다 높은 가격으로 

콜옵션 계약을 맺을까요?

 

단순히 계산해봐도 65000원까지 주가가 오를 것 같다면

60000원에 주식을 사는게 이득일텐데요.

 

 

바로 레버리지 때문입니다.

콜옵션 매도자는 콜옵션 매수자에게 일정 수수료를 받습니다.

 

만약 콜옵션 매수자가 옵션 계약 대신,

현물 주식을 산다면 60000원이 들겠지만,

콜옵션을 매수하면 더 적은 비용으로 주가 상승의 수혜를 볼 수 있습니다.

 

물론 옵션 계약 조건이 현물 주식을 사는 것보다 좀 더 불리하긴하죠.

60000원이 아닌 더 높은 가격인 65000원에 살 권리이니까요.

 


그렇다면 매도자는 왜 콜옵션 매도 포지션을 잡은걸까요?

 

대표적으로 두가지 경우의 수가 있습니다.

 

주식을 장기간 보유하고 싶긴한데,

한동안 주가가 크게 상승할 것 같지 않아

콜옵션 매도 수수료를 통해 현금 흐름을 만들고싶은 투자자이거나,

 

매도하고싶은 주식이 있는데, 프리미엄을 통해 더 많은 돈을 벌고싶은 사람일겁니다.

 


그럼 주식을 매도하는 투자자는

모두 콜옵션 매도를 이용하면 되지않냐는 의문이 들겁니다.

 

빨리 처분해야하는게 아니라면 프리미엄도 받을 수 있으니까요.

 

하지만 우리나라는 개별종목 옵션거래가 개인 투자자에게 허용되지 않습니다.

 

해외의 경우에도 투자금이 일정 이상이 아니면, 옵션거래에 접근하기 어렵고요.

 

그래서 전 암호화폐 옵션거래를 이용해보려합니다.

 

암호화페는 아직 제도권에 있지 않아, 개인의 옵션거래 원활한 편입니다.

 


일단 저번 코드를 이어 작성해봅시다.

 

Deribit에서 옵션 티커를 받아와보니 두가지 형식이 존재했습니다.

 

#받아온 데이터 파싱
import ccxt
from datetime import datetime

a = deribit.fetch_tickers()

def get_K_call_put(date_string):

    # Split the string by '-'
    date_string_copy = date_string
    date_string_split = date_string.split("-")
    # print(date_string_split)
    if len(date_string_split) == 4 and len(date_string_split[1]) == 7:
        # Extract the date string from the list
        date_string = date_string_split[1]

        # Convert the date string to a datetime object
        date = datetime.strptime(date_string, '%d%b%y')
        new_date_format = date.strftime("%Y-%m-%d")
        print(date_string_split, new_date_format, date_string_copy)
        return date_string_split, new_date_format

    else:
        return 0,0
        
#ccxt모듈을 이용해 가져온 중첩 딕셔너리 데이터의 키값과 벨류 값을 우리가 만든 함수에 넣어봅시다.
for key, val in a.items():
    get_K_call_put(key)

 

위 코드는 아래 두 데이터를 분류하고 한가지 날짜 형식만 남깁니다.

BTC-24FEB23-21500-C        BTC-230224-21500-C

 

 BTC-230224-21500-C 형식은 가격데이터를 불러올 수 없는 형식이므로 삭제하겠습니다.

 

 

이런 값이 나올겁니다.

만기날짜, 옵션계약 수행가격, 풋-콜 옵션 구분

이 순서로 데이터를 추출할 수 있습니다.

 

 


 

더보기
  • timestamp: The time the data was collected, represented as a UNIX timestamp in milliseconds (1676052955190 milliseconds since 1970-01-01T00:00:00Z).
  • datetime: The time the data was collected, represented as a ISO 8601 string in the UTC timezone (2023-02-10T18:15:55.190Z).
  • high: The highest price that the contract traded at during the time frame represented by the data (0.0495 USD).
  • low: The lowest price that the contract traded at during the time frame represented by the data (0.0365 USD).
  • bid: The highest price that a buyer is willing to pay for the contract at the time of the data collection (0.039 USD).
  • bidVolume: The number of contracts being offered at the bid price (13.9 contracts).
  • ask: The lowest price that a seller is willing to accept for the contract at the time of the data collection (0.0405 USD).
  • askVolume: The number of contracts being offered at the ask price (23.5 contracts).
  • vwap: The volume-weighted average price, which is a measure of the average price of the contract taking into account the volume traded at each price point. The value is None in this case, indicating that this information is not available.
  • open: The opening price of the contract for the time frame represented by the data. The value is None in this case, indicating that this information is not available.
  • close: The closing price of the contract for the time frame represented by the data (0.038 USD).
  • last: The last price at which the contract traded (0.038 USD).
  • previousClose: The closing price of the contract for the previous time frame. The value is None in this case, indicating that this information is not available.
  • change: The difference between the current price and the previous close. The value is None in this case, indicating that this information is not available.
  • percentage: The percentage change between the current price and the previous close. The value is None in this case, indicating that this information is not available.
  • average: The average price of the contract over the time frame represented by the data. The value is None in this case, indicating that this information is not available.
  • baseVolume: The total number of contracts traded over the time frame represented by the data. The value is None in this case, indicating that this information is not available.
  • quoteVolume: The total amount of currency traded in the contract over the time frame represented by the data (11.5 USD).
  • info: Additional information about the contract, including the underlying price, index, and various statistics and parameters such as the volume traded, minimum and maximum prices, and the bid and ask implied volatility.

ChatGPT에게 티커로 불러온 옵션 데이터의 해석을 맡겨봤습니다.

 

훌륭하네요.

 

close라는 이름을 가진 데이터가 해당 옵션의 현재가 인듯 합니다.

 

한가지 오류가 있는데요, 

close price의 단위를 USD로 표시하고 있습니다.

 

실제로는 BTC개수로 포시되고 있습니다.

 

예를들어 BTC가 1개가 $30000라면 옵션 거래가는 $(0.38*60000)인거죠.

 


이제 실제 거래를 위한 전략을 세우면 완성입니다.

 

다음 글에선 가격 변동범위를 계산하여 전략 실행 지점을 찾아보도록 하겠습니다.

반응형

댓글