### 명세서 #########################################################################
"""
1. 사용전략 : 20일고가돌파, 터틀불타기
2. 조건
(종목선정)
내 selcect
(매수)
1. 20일 중 최고가 돌파
2. 고점돌파가 아닌 눌림매수로 바꿈
20일 고점과 저점의 피보나치 0.382, 0.5까지 내려갔다가 상승하면 매수
(매도)
10일 중 최저가 돌파
2-atr 하락시
(추가매수)
1-atr 상승시
[변경내역]
(23.12.10)
1. 고점돌파가 아닌 눌림매수로 바꿈
20일 고점과 저점의 피보나치 0.382, 0.5까지 내려갔다가 상승하면 매수
2. purchase list 방출조건 추가
가. 20일 저가 하향돌파시 방출
(23.12.11)
1. 트레일링스탑 조건 고민
atr 1차 매수하고 나면 수익류링 절반으로 줄어서 매도해버린다.
atr 매수하면 수익률=1%로 변경
atr 매수 후 수익류0%이하되면 매도
2. 20일 고점돌파시 추가매수(개발중)
종가에 20일 고점돌파하면 check에 True 넣고(이건종가에만 업데이트)
그 다음부터 눌려서 20일고점 1.05 안에 있다면 매수
(23.12.12)
1. 피보나치 눌림목 너무 자주사는데 종가에만 사도록 하고 메시지 보내도록 한다.
2. atr 매수값 0.5art로 바꿈
3. 트레일링 스탑 미사용
(23.12.21)
1. 종가에서만 피보나치 적용하도록
2. (고민중)20일 저가를 최초매수로 잡으니까 너무 떨어져도 안 판다 (근데 이게 맞을수도?)
(이미 atr에서 팔았어야 하는데 안 파네)
"""
###################################################################################
# 장이 열리는날이 아니면 프로그램 종료 #############################################################
import exchange_calendars as ecals
import datetime as dt
from Util_discord_message import send_message
XKRX = ecals.get_calendar("XKRX") # 한국 코드
ismarketopen = XKRX.is_session(dt.date.today().strftime("%Y-%m-%d")) # 오늘은 개장일인지 확인
if ismarketopen == False: # 장 닫혔으면 종료한다.
exit(0)
else: # 장 열려으면 시작한다.
send_message(f'[전략명 : 20일 고가, 10일 저가 전략] 시작합니다')
#############################################################################################
#############################################################################################
#############################################################################################
import sys, atexit, requests, time, json, pymysql, yaml, pprint
import pandas as pd
import Util_Hankook_KR_V3_devel_231114 as hk
import Util_Analysis_V3_devel_231114 as anal
from Util_get_access_token import get_access_token_daily
#############################################################################################
#############################################################################################
# 사용계좌 선택 / 디스코드 선택#####################################################################
with open('00_config.yaml', encoding='UTF-8') as f:
_cfg = yaml.load(f, Loader=yaml.FullLoader)
app_key = _cfg['APP_KEY']
app_secret = _cfg['APP_SECRET']
acc_no = _cfg['CANO']
acc_flag = _cfg['ACNT_PRDT_CD']
url_base = _cfg['URL_BASE']
discord_url = _cfg['DISCORD_WEBHOOK_URL']
##################################################################################################
##################################################################################################
### 엑세스토큰 발급, 클래스 선언 #########################################################3
access_token = get_access_token_daily()
# approval_key = get_approval_key(app_key,app_secret,url_base)
hk_sd = hk.Stock_data()
buy = hk.Order_buy()
sell = hk.Order_sell()
acc = hk.Account_Info()
dbu = hk.DB_Updater()
hk_cm = hk.Common_util()
anal_ma = anal.Ma()
anal_bb = anal.Bb()
anal_atr = anal.ATR()
anal_sd = anal.Stock_data()
anal_sd_db = anal.Stock_data_using_db()
anal_mt = anal.Market_timing()
anal_hl = anal.High_Low()
#########################################################################################
# 공통함수 선언 #############################################################################
# 터틀방식 그대로 20일 고가, 10일 저가
def buy_condition_def(code):
bought_list = acc.get_holding_stock_list()
high_ndays = 20
low_ndays = 10
signal = anal_mt.break_throgh_high_low_price_ndays_ndays(code, high_ndays, low_ndays)
# 매수 안 했다면 20일 고가 돌파시 산다
if code not in bought_list and signal == True:
buy_condition = True
# 매수했다면 10일 저가를 하향 돌파시 판다
elif code in bought_list and signal == False:
buy_condition = False
# 그 외에는 ATR 매매만 한다.
else:
buy_condition = "nothing"
return buy_condition
# 12개월 이동평균선 사용
def get_div_rate_using_ma(code):
a = anal_sd.get_current_price(code)
ma_1 = anal_ma.get_sma_value(code, 20)
ma_2 = anal_ma.get_sma_value(code, 40)
ma_3 = anal_ma.get_sma_value(code, 60)
ma_4 = anal_ma.get_sma_value(code, 80)
ma_5 = anal_ma.get_sma_value(code, 100)
ma_6 = anal_ma.get_sma_value(code, 120)
ma_7 = anal_ma.get_sma_value(code, 140)
ma_8 = anal_ma.get_sma_value(code, 160)
ma_9 = anal_ma.get_sma_value(code, 180)
ma_10 = anal_ma.get_sma_value(code, 200)
ma_11 = anal_ma.get_sma_value(code, 220)
ma_12 = anal_ma.get_sma_value(code, 240)
temp_no = 12
if a < ma_1:
temp_no -= 1
if a < ma_2:
temp_no -= 1
if a < ma_3:
temp_no -= 1
if a < ma_4:
temp_no -= 1
if a < ma_5:
temp_no -= 1
if a < ma_6:
temp_no -= 1
if a < ma_7:
temp_no -= 1
if a < ma_8:
temp_no -= 1
if a < ma_9:
temp_no -= 1
if a < ma_10:
temp_no -= 1
if a < ma_11:
temp_no -= 1
if a < ma_12:
temp_no -= 1
if temp_no <= 1:
temp_no = 1
division_rate = temp_no / 12
return division_rate
# 공통함수 선언(끝) #############################################################################
# 데이타 관리하기(시작) ############################################################################################
if True:
t_now = dt.datetime.now()
today_date_str = dt.datetime.now().strftime('%Y-%m-%d')
bought_list = acc.get_holding_stock_list()
kofr_code = "423160" # kodex kofr
# add_list 관리하기(시작) ###########################################################################################
if True:
try:
with open("add_list.json", 'r', encoding='utf-8') as temp_in: # 불러오기
add_list = json.load(temp_in)
except FileNotFoundError: # 파일 없으면 최초로 만듬
# 일단 선언하고
add_list = ['011500', '014820', '004140', '024720', '030350', '071200', '080720', '119860', '148150', '203450', '042000', '032300', '122640', '399720', '060250', '330860', '377300', '026940', '102120', '321820', '006200', '091810', '353810', '247540', '393890', '454910', '425040', '018700', '025770']
# 저장하고 불러오기
with open("add_list.json", 'w', encoding='utf-8') as temp_out:
json.dump(add_list, temp_out, ensure_ascii=False, indent=4)
with open("add_list.json", 'r', encoding='utf-8') as temp_in:
add_list = json.load(temp_in)
# add_list 관리하기(끝) ###########################################################################################
# add_list 관리하기(끝) ###########################################################################################
# purchase_data 관리하기(시작) #########################################################################################
if True:
# 키이름 변수로 할당
key_date = "date"
key_name = "name"
key_high_price = "high_price"
key_low_price = "low_price"
key_fibo_0382_check = "fibo_0.382_check"
key_fibo_0382_price = "fibo_0.382_price"
key_fibo_05_check = "fibo_0.5_check"
key_fibo_05_price = "fibo_0.5_price"
key_add_date = "add_date"
# purchase_data관리하기_1. 파일이 있다면 읽어오고 업데이트 아니라면 새로 만든다.
try:
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
purchase_data = json.load(temp_in)
# purchase_data관리하기_2. 파일 없으면 add_list를 기준으로 최초로 만듬
except FileNotFoundError:
# 가. 일단 선언하고
purchase_data = {}
# 나. 날짜 초기화
purchase_data[key_date] = today_date_str
# 다-1. purchase_data 초기생성 : add_list를 가지고 만든다
for code in add_list.copy():
add_list.remove(code)
name = hk_sd.get_stock_name(code)
current_price = anal_sd.get_current_price(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
add_date = today_date_str
fibo_0382_price = high_price - 0.382 * (high_price - low_price)
fibo_05_price = high_price - 0.5 * (high_price - low_price)
# 일단 만들기
purchase_data[code] = {key_name: name,
key_high_price: high_price,
key_low_price: low_price,
key_fibo_0382_check: False,
key_fibo_0382_price: fibo_0382_price,
key_fibo_05_check: False,
key_fibo_05_price: fibo_05_price,
key_add_date: add_date}
# 업데이트하기(필요없음)
purchase_data[code][key_name] = name
purchase_data[code][key_high_price] = high_price
purchase_data[code][key_low_price] = low_price
if current_price < purchase_data[code][key_fibo_0382_price]:
purchase_data[code][key_fibo_0382_check] = True
purchase_data[code][key_fibo_0382_price] = fibo_0382_price
if current_price < purchase_data[code][key_fibo_05_price]:
purchase_data[code][key_fibo_05_check] = True
purchase_data[code][key_fibo_05_price] = fibo_05_price
purchase_data[code][key_add_date] = add_date
# 다-2. 저장하고 불러오기
with open("add_list.json", 'w', encoding='utf-8') as temp_out:
json.dump(add_list, temp_out, ensure_ascii=False, indent=4)
with open("add_list.json", 'r', encoding='utf-8') as temp_in:
add_list = json.load(temp_in)
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# 날짜보고 업데이트 실행 #################################################################################
# 오늘 날짜라면 오늘 처음이거나 중간에 멈추고 다시시작한거다 기존데이터에 카운터가 있으니까 그대로
if purchase_data['date'] == today_date_str:
pass
# with open("purchase_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
# purchase_data = json.load(temp_in)
# 오늘 날짜아니라면 업데이트 한다.
else:
# 일단 읽어와서
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# 오늘 일자값으로 업데이트 한다.
purchase_data[key_date] = today_date_str # 오늘날짜 업데이트
# 2-1. bought_list에 있다면 이미 산거다 지워라
for code in bought_list.copy():
if code in purchase_data.copy().keys():
del purchase_data[code]
# 2-2. 저장하고 불러오기
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# 3-1. add_list에 종목이 있으면 추가하고 add_list에서는 삭제
for code in add_list.copy():
if code not in purchase_data.copy().keys():
add_list.remove(code)
name = hk_sd.get_stock_name(code)
current_price = anal_sd.get_current_price(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
add_date = today_date_str
fibo_0382_price = high_price - 0.382 * (high_price - low_price)
fibo_05_price = high_price - 0.5 * (high_price - low_price)
# 일단 만들기
purchase_data[code] = {key_name: name,
key_high_price: high_price,
key_low_price: low_price,
key_fibo_0382_check: False,
key_fibo_0382_price: fibo_0382_price,
key_fibo_05_check: False,
key_fibo_05_price: fibo_05_price,
key_add_date: add_date}
# 업데이트하기(필요없음)
purchase_data[code][key_name] = name
purchase_data[code][key_high_price] = high_price
purchase_data[code][key_low_price] = low_price
if current_price < purchase_data[code][key_fibo_0382_price]:
purchase_data[code][key_fibo_0382_check] = True
purchase_data[code][key_fibo_0382_price] = fibo_0382_price
if current_price < purchase_data[code][key_fibo_05_price]:
purchase_data[code][key_fibo_05_check] = True
purchase_data[code][key_fibo_05_price] = fibo_05_price
purchase_data[code][key_add_date] = add_date
# 3-2. 저장하고 불러오기, add_list도 purchase_data에 추가됐으면 삭제했으니까 저장한다.
with open("add_list.json", 'w', encoding='utf-8') as temp_out:
json.dump(add_list, temp_out, ensure_ascii=False, indent=4)
with open("add_list.json", 'r', encoding='utf-8') as temp_in:
add_list = json.load(temp_in)
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# 30일동안 매수하지 못했다면 종목 제거, # 20일 저가보다 낮다면 제거
for code in purchase_data.copy().keys():
if code == key_date:
continue
else:
current_price = anal_sd.get_current_price(code)
if t_now - dt.datetime.strptime(purchase_data[code][key_add_date], '%Y-%m-%d') > dt.timedelta(
days=30) or current_price < purchase_data[code][key_low_price]:
del purchase_data[code]
with open("purchase_data.json", 'w', encoding='UTF-8') as temp_out: # 저장
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='UTF-8') as temp_in: # 불러오기
purchase_data = json.load(temp_in)
# 피보나치 눌림목 업데이트
for code in purchase_data.copy().keys():
if code == 'date':
continue
name = hk_sd.get_stock_name(code)
current_price = anal_sd.get_current_price(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
add_date = today_date_str
fibo_0382_price = high_price - 0.382 * (high_price - low_price)
fibo_05_price = high_price - 0.5 * (high_price - low_price)
# 일단 만들기
purchase_data[code] = {key_name: name,
key_high_price: high_price,
key_low_price: low_price,
key_fibo_0382_check: False,
key_fibo_0382_price: fibo_0382_price,
key_fibo_05_check: False,
key_fibo_05_price: fibo_05_price,
key_add_date: add_date}
# 업데이트하기(필요없음)
purchase_data[code][key_name] = name
purchase_data[code][key_high_price] = high_price
purchase_data[code][key_low_price] = low_price
if current_price < purchase_data[code][key_fibo_0382_price]:
purchase_data[code][key_fibo_0382_check] = True
purchase_data[code][key_fibo_0382_price] = fibo_0382_price
if current_price < purchase_data[code][key_fibo_05_price]:
purchase_data[code][key_fibo_05_check] = True
purchase_data[code][key_fibo_05_price] = fibo_05_price
purchase_data[code][key_add_date] = add_date
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# purchase_data 관리하기 (끝) #########################################################################################
# purchase_data 관리하기 (끝) #########################################################################################
# bought 데이터 관리하기(시작) ###########################################################################################
if True:
try:
with open("bought_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
bought_data = json.load(temp_in)
except FileNotFoundError: # 파일 없으면 bought_list를 가지고 최초로 만듬
# 일단 선언하고
bought_data = {}
# 일자 업데이트
bought_data['date'] = today_date_str
# bought_data 초기화
if len(bought_list) > 0:
for code in bought_list:
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 일단 만들기
bought_data[code] = {'name': name,
'first_buy_date': today_date_str,
'last_buy_price': current_price,
'atr': stock_atr,
'atr_buy_price': 0,
'atr_sell_price': 0,
'sma_55': sma_55,
'sma_55_check': False,
'max_yield_rate': 0,
'max_yield_check': False,
'high_price': high_price,
'low_price': low_price}
# 데이타 업데이트
bought_data[code]['name'] = name
bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code]['last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code]['last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code]['max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
bought_data[code]['high_price'] = high_price
bought_data[code]['low_price'] = low_price
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# (시작) 오늘값으로 업데이트, 같다면 그냥 읽어오기만#####################################################################
# 가-1. 오늘값으로 업데이트
if bought_data['date'] == today_date_str: # 오늘 날짜라면 오늘 처음이거나 중간에 멈추고 다시시작한거다 기존데이터에 카운터가 있으니까 그대로
pass
# with open("bought_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
# bought_data = json.load(temp_in)
# 가-2. 날짜가 다르면 업데이트, data, list 비교해서 추가 및 삭제
else:
# 일단 읽어와서
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 날짜 바꾸고
bought_data['date'] = today_date_str # 오늘날짜 업데이트
# 가. bought리스트에 있는데 data에 없다 : "신규" 추가해라
# 가-1. 신규생성
for code in bought_list:
if code == kofr_code:
continue
elif code not in bought_data.copy().keys():
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 일단 만들기
bought_data[code] = {'name': name,
'first_buy_date': today_date_str,
'last_buy_price': current_price,
'atr': stock_atr,
'atr_buy_price': 0,
'atr_sell_price': 0,
'sma_55': sma_55,
'sma_55_check': False,
'max_yield_rate': 0,
'max_yield_check': False,
'high_price': high_price,
'low_price': low_price}
# 데이타 업데이트
bought_data[code]['name'] = name
bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code]['last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code]['last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code]['max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
bought_data[code]['high_price'] = high_price
bought_data[code]['low_price'] = low_price
# 가-2. 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 나. bought data에 있는데 bought_list에 없다 : 삭제
for code in bought_data.copy().keys():
if code == kofr_code:
continue
elif code not in bought_list:
del bought_data[code]
# 나. 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 다. 위에서 비교 후 추가 및 삭제했으니 남은 놈들은 필요한 사항만 업데이트
for code in bought_data.copy().keys():
if code == kofr_code:
continue
else:
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 데이타 업데이트 : 필요한 놈만 해야한다.
bought_data[code]['name'] = name
# bought_data[code]['first_buy_date'] = today_date_str
# bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code]['last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code][
'last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code][
'max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
# bought_data[code]['high_price'] = low_price
# bought_data[code]['low_price'] = low_price
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# (끝) 오늘값으로 업데이트, 같다면 그냥 읽어오기만#####################################################################
# (끝) 오늘값으로 업데이트, 같다면 그냥 읽어오기만#####################################################################
# 데이타 관리하기(끝) ############################################################################################
# 프로그램 수행부###########################################################################################################
if True:
print(f'Gen 03_돌파매매 & 터틀방식 프로그램 시작합니다.')
t_now = dt.datetime.now()
atexit.register(send_message, f"[{t_now}]=프로그램 종료됨=")
today_date_str = dt.datetime.now().strftime('%Y-%m-%d')
kofr_code = "423160" # kodex kofr
total_amount, current_cash, bought_list = acc.update_account_info()
unit_amount = int(total_amount / 50) # 기본 50 이걸 시장상황에 따라 바꿀까? 많이 저점일때는 분할수를 작게
onetime_001, onetime_002, onetime_003, onetime_004, onetime_005 = True, True, True, True, True
# 반복 수행부
while True:
try:
t_now = dt.datetime.now()
t_0900 = t_now.replace(hour=9, minute=0, second=0, microsecond=0)
t_1500 = t_now.replace(hour=15, minute=0, second=0, microsecond=0)
t_1510 = t_now.replace(hour=15, minute=10, second=0, microsecond=0)
t_1519 = t_now.replace(hour=15, minute=19, second=0, microsecond=0)
t_1520 = t_now.replace(hour=15, minute=20, second=0, microsecond=0)
t_1530 = t_now.replace(hour=15, minute=30, second=0, microsecond=0)
# 5분단위 값 업데이트(시작) ########################################################################################
if (t_now.minute % 5) == 0:
print(f'5분 단위 업데이트 ')
# 파일 업데이트 된거 있으면 저장하고 불러오기
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out: # 저장
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
time.sleep(0.1)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
purchase_data = json.load(temp_in)
time.sleep(0.1)
# 파일 업데이트 된거 있으면 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out: # 저장
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
time.sleep(0.1)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in: # 불러오기
bought_data = json.load(temp_in)
time.sleep(0.1)
# 계좌정보 업데이트
bought_list = acc.get_holding_stock_list()
# 5분단위 값 업데이트 (끝)########################################################################################
# 장중 매수 : 구매리스트 20일고가 / 기매수종목 atr 매수,매도
if t_0900 < t_now < t_1519:
for code in purchase_data.copy().keys():
if code == 'date':
continue
name = purchase_data[code][key_name]
current_price = anal_sd.get_current_price(code)
unit_amount_adj = unit_amount
# 최초 매수 (20일 고가)
if (code not in bought_data.keys()) and current_price > purchase_data[code][key_high_price]:
send_message(f'[{name}] 20일고가 돌파 최초매수 진행합니다.')
send_message(f'20일 고가 : {purchase_data[code][key_high_price]}')
current_cash = acc.get_possible_order_cash()
trans_amount = current_price * anal_sd_db.get_volume_before_ndays(code, -1)
if unit_amount_adj > trans_amount * (1 / 2000):
send_message(f'거래대금 때문에 매수금액 조정합니다')
unit_amount_adj = trans_amount * (1 / 2000)
if current_cash > unit_amount_adj:
buy.bid_1(code, unit_amount_adj)
if current_cash < unit_amount_adj:
hk_cm.make_money_using_kofr(unit_amount_adj - current_cash)
buy.bid_1(code, unit_amount_adj)
# 매수했으니까 purchase data에서 삭제
del purchase_data[code]
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 일단 만들기
bought_data[code] = {'name': name,
'first_buy_date': today_date_str,
'last_buy_price': current_price,
'atr': stock_atr,
'atr_buy_price': 0,
'atr_sell_price': 0,
'sma_55': sma_55,
'sma_55_check': False,
'max_yield_rate': 0,
'max_yield_check': False,
'high_price': high_price,
'low_price': low_price}
# 데이타 업데이트
bought_data[code]['name'] = name
bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code]['last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code]['last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code]['max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
bought_data[code]['high_price'] = high_price
bought_data[code]['low_price'] = low_price
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 저장하고 불러오기
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# (신규매수)purchase 데이터 중에서 20일 고가 돌파하면 산다. (끝) ###############################################
# (신규매수)purchase 데이터 중에서 20일 고가 돌파하면 산다. (끝) ###############################################
# bought_data 중에서 1. atr 매수/매도, 2. 20일 저가시 매도, 3. 55일 이평하향시 매도(미사용), 4. 트레일링스탑(미사용) ###############
for code in bought_data.copy().keys():
if code == 'date':
continue
name = bought_data[code]['name']
current_price = anal_sd.get_current_price(code)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
unit_amount_adj = unit_amount
# max_yield_rate, check 업데이트
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
if yield_rate > 10 and bought_data[code]['max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
# 1-1. ATR 매수
if (code in bought_data.keys()) and current_price > bought_data[code][
'atr_buy_price'] and hold_amt < total_amount * 0.05:
send_message(f'[{name}] ATR 추가매수 진행합니다.')
current_cash = acc.get_possible_order_cash()
trans_amount = current_price * anal_sd_db.get_volume_before_ndays(code, -1)
if unit_amount_adj > trans_amount * (1 / 2000):
send_message(f'거래대금 때문에 매수금액 조정합니다')
unit_amount_adj = trans_amount * (1 / 2000)
if current_cash > unit_amount_adj:
buy.bid_1(code, unit_amount_adj)
if current_cash < unit_amount_adj:
hk_cm.make_money_using_kofr(unit_amount_adj - current_cash)
buy.bid_1(code, unit_amount_adj)
# 데이타 업데이트 ##########################################################################
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
# bought_data[code]['name'] = name
# bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code]['last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code]['last_buy_price'] - 2 * stock_atr
bought_data[code]['max_yield_rate'] = 1 # atr매수하고나면 수익률이 급감하니까 미리 1로 맞춰놓고 max값을 자동업데이트하도록
# bought_data[code]['sma_55'] = sma_55
# if current_price > sma_55:
# bought_data[code]['sma_55_check'] = True
# else:
# pass
# if yield_rate > bought_data[code]['max_yield_rate']:
# bought_data[code]['max_yield_rate'] = yield_rate
# else:
# pass
# if bought_data[code]['max_yield_rate'] > 10 and bought_data[code][
# 'max_yield_check'] == False:
# bought_data[code]['max_yield_check'] = True
# else:
# pass
# bought_data[code]['low_price'] = low_price
# (끝) 데이타 업데이트 ##########################################################################
# (끝) 데이타 업데이트 ##########################################################################
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 1-2. ATR매도
if code in bought_data.keys() and current_price < bought_data[code]['atr_sell_price']:
send_message(f'[{name}] ATR_매도 진행합니다.')
sell.ask_1(code, hold_qty)
# 변수 update
del bought_data[code]
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 2. 20일저가 하향돌파로 매도
if code in bought_data.keys() and current_price < bought_data[code]['low_price']:
send_message(f'[{name}]_20일 저가 하향돌파로 ""매도"" 진행합니다.')
sell.ask_1(code, hold_qty)
del bought_data[code]
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 3. 트레일링 스탑(미사용)
# if code in bought_data.keys() and bought_data[code]['max_yield_check'] == True and bought_data[code]['max_yield_rate'] > 10 and yield_rate < 0.5* bought_data[code]['max_yield_rate']:
# send_message(f'[{name}] 트레일링_스탑(1/2 최대수익)_매도 진행합니다.')
# send_message(f'수익률 : {yield_rate}, max수익률 : {bought_data[code]["max_yield_rate"]}')
#
# sell.ask_1(code, hold_qty)
#
# # 변수 update
# del bought_data[code]
#
# # 저장하고 불러오기
# with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
# json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
# with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
# bought_data = json.load(temp_in)
#
# elif code in bought_data.keys() and bought_data[code]['max_yield_check'] == True and yield_rate < 0:
#
# send_message(f'[{name}] 트레일링_스탑(추가매수 후 0%)_매도 진행합니다.')
#
# sell.ask_1(code, hold_qty)
#
# # 변수 update
# del bought_data[code]
#
# # 저장하고 불러오기
# with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
# json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
# with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
# bought_data = json.load(temp_in)
# (끝) bought_data 중에서 1. atr 매수/매도, 2. 10일저가시 매도, 3. 55일 이평하향시 매도 ###############################
# (끝) bought_data 중에서 1. atr 매수/매도, 2. 10일저가시 매도, 3. 55일 이평하향시 매도 ###############################
# 장중 매수 : 피보나치 돌파시 매수
if t_1510 < t_now < t_1519:
# (신규매수)purchase 데이터 중에서 피보나치 돌파하면 산다.####################################################
for code in purchase_data.copy().keys():
if code == 'date':
continue
name = purchase_data[code][key_name]
current_price = anal_sd.get_current_price(code)
unit_amount_adj = unit_amount
# 최초 매수 (피보나치 0.382돌파)
if (code not in bought_data.keys()) and purchase_data[code][
key_fibo_0382_check] == True and current_price > purchase_data[code][
key_fibo_0382_price]:
send_message(f'[{name}]')
send_message(f'피보나치 0.382 눌림목 돌파 최초매수 진행합니다.')
send_message(f'0.382가격 : {purchase_data[code][key_fibo_0382_price]}')
current_cash = acc.get_possible_order_cash()
trans_amount = current_price * anal_sd_db.get_volume_before_ndays(code, -1)
if unit_amount_adj > trans_amount * (1 / 2000):
send_message(f'거래대금 때문에 매수금액 조정합니다')
unit_amount_adj = trans_amount * (1 / 2000)
if current_cash > unit_amount_adj:
buy.bid_1(code, unit_amount_adj)
if current_cash < unit_amount_adj:
hk_cm.make_money_using_kofr(unit_amount_adj - current_cash)
buy.bid_1(code, unit_amount_adj)
# 매수했으니까 purchase data에서 삭제
del purchase_data[code]
# 신규매수 했으니까 bought_data 추가
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 일단 만들기
bought_data[code] = {'name': name,
'first_buy_date': today_date_str,
'last_buy_price': current_price,
'atr': stock_atr,
'atr_buy_price': 0,
'atr_sell_price': 0,
'sma_55': sma_55,
'sma_55_check': False,
'max_yield_rate': 0,
'max_yield_check': False,
'high_price': high_price,
'low_price': low_price}
# 데이타 업데이트
bought_data[code]['name'] = name
bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code][
'last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code][
'last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code][
'max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
bought_data[code]['high_price'] = high_price
bought_data[code]['low_price'] = low_price
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 저장하고 불러오기
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# (신규매수)purchase 데이터 중에서 피보나치 돌파하면 산다. (끝) ###############################################
# (신규매수)purchase 데이터 중에서 피보나치 돌파하면 산다. (끝) ###############################################
# 최초 매수 (피보나치 0.5 눌림 후 돌파)
if (code not in bought_data.keys()) and purchase_data[code][
key_fibo_05_check] == True and current_price > purchase_data[code][
key_fibo_05_price]:
send_message(f'[{name}]')
send_message(f'피보나치 0.5 눌림목 돌파 최초매수 진행합니다.')
send_message(f'0.5가격 : {purchase_data[code][key_fibo_0382_price]}')
current_cash = acc.get_possible_order_cash()
trans_amount = current_price * anal_sd_db.get_volume_before_ndays(code, -1)
if unit_amount_adj > trans_amount * (1 / 2000):
send_message(f'거래대금 때문에 매수금액 조정합니다')
unit_amount_adj = trans_amount * (1 / 2000)
if current_cash > unit_amount_adj:
buy.bid_1(code, unit_amount_adj)
if current_cash < unit_amount_adj:
hk_cm.make_money_using_kofr(unit_amount_adj - current_cash)
buy.bid_1(code, unit_amount_adj)
# 매수했으니까 purchase data에서 삭제
del purchase_data[code]
# 신규매수 했으니까 bought_data 추가
name = hk_sd.get_stock_name(code)
stock_atr = anal_atr.get_atr_value_ndays(code, 5)
current_price = anal_sd.get_current_price(code)
sma_55 = anal_ma.get_sma_value(code, 55)
hold_qty, hold_amt, yield_rate, yield_amt = acc.get_one_stock_balance(code)
high_price = anal_hl.get_last_high_price(code, 20)
low_price = anal_hl.get_last_low_price(code, 20)
# 일단 만들기
bought_data[code] = {'name': name,
'first_buy_date': today_date_str,
'last_buy_price': current_price,
'atr': stock_atr,
'atr_buy_price': 0,
'atr_sell_price': 0,
'sma_55': sma_55,
'sma_55_check': False,
'max_yield_rate': 0,
'max_yield_check': False,
'high_price': high_price,
'low_price': low_price}
# 데이타 업데이트
bought_data[code]['name'] = name
bought_data[code]['first_buy_date'] = today_date_str
bought_data[code]['last_buy_price'] = current_price
bought_data[code]['atr'] = stock_atr
bought_data[code]['atr_buy_price'] = bought_data[code][
'last_buy_price'] + 0.5 * stock_atr
bought_data[code]['atr_sell_price'] = bought_data[code][
'last_buy_price'] - 2 * stock_atr
bought_data[code]['sma_55'] = sma_55
if current_price > sma_55:
bought_data[code]['sma_55_check'] = True
else:
pass
if yield_rate > bought_data[code]['max_yield_rate']:
bought_data[code]['max_yield_rate'] = yield_rate
else:
pass
if bought_data[code]['max_yield_rate'] > 10 and bought_data[code][
'max_yield_check'] == False:
bought_data[code]['max_yield_check'] = True
else:
pass
bought_data[code]['high_price'] = high_price
bought_data[code]['low_price'] = low_price
# 저장하고 불러오기
with open("bought_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(bought_data, temp_out, ensure_ascii=False, indent=4)
with open("bought_data.json", 'r', encoding='utf-8') as temp_in:
bought_data = json.load(temp_in)
# 저장하고 불러오기
with open("purchase_data.json", 'w', encoding='utf-8') as temp_out:
json.dump(purchase_data, temp_out, ensure_ascii=False, indent=4)
with open("purchase_data.json", 'r', encoding='utf-8') as temp_in:
purchase_data = json.load(temp_in)
# (신규매수)purchase 데이터 중에서 피보나치 돌파하면 산다. (끝) ###############################################
# (신규매수)purchase 데이터 중에서 피보나치 돌파하면 산다. (끝) ###############################################
if t_1519 < t_now:
send_message(f'장 마감 전 KOFR 매수합니다')
total_amount, current_cash, bought_list = acc.update_account_info()
if current_cash > 500000:
buy.ask_1(kofr_code, current_cash)
send_message(f'15시20분 이후 프로그램 종료')
exit(0)
# #매시간 알림
# if t_now.minute == 0 and t_now.second <= 15:
# send_message(f'프로그램 동작중')
# time.sleep(10)
except requests.packages.urllib3.exceptions.MaxRetryError:
send_message(f'Max Retry Error 60초 대기 후 재실행')
time.sleep(60)
except requests.packages.urllib3.exceptions.ConnectionError:
send_message(f'Connection 에러발생 60초 대기 후 재실행')
time.sleep(60)
except requests.exceptions.ConnectionError:
send_message(f'Connection 에러 2번째 발생 60초 대기 후 재실행')
time.sleep(60)
except Exception as ex:
send_message(f'Main 오류발생 :{ex}')
exit(0)
except Exception as e:
send_message(f"[오류 발생] : {e}")
exit(0)
To embed this project on your website, copy the following code and paste it into your website's HTML: