This commit is contained in:
dsyoon
2023-01-21 19:29:02 +09:00
parent 0773343fb4
commit 4a453f36b6
6 changed files with 574 additions and 25 deletions

472
Bithumb.py Normal file
View File

@@ -0,0 +1,472 @@
import pybithumb
from hts.HTS import HTS
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import plotly.graph_objects as go
from plotly import subplots
import plotly.io as po
from math import nan
import csv
import os
from hts.BuySellChecker import BuySellChecker
from datetime import datetime
from stock.analysis.AnalyzerSqlite import AnalyzerSqlite
class Bithumb(HTS):
RESOURCE_PATH = None
buySellChecker = None
analyzerSqlite = None
log_filename = None
def __init__(self, RESOURCE_PATH):
super().__init__(RESOURCE_PATH)
self.RESOURCE_PATH = RESOURCE_PATH
con_key = "946dd0b0e6f8ad411144cd33f09518d3" # 본인의 Connect Key를 입력한다.
sec_key = "56b2a3cdd9fe3a82aa3f38c97c161125" # 본인의 Secret Key를 입력한다.
# bithumb api에 연결한 클라스 객체를 선언한다.
self.bithumb = pybithumb.Bithumb(con_key, sec_key)
self.buySellChecker = BuySellChecker()
self.analyzerSqlite = AnalyzerSqlite()
self.log_filename = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb', 'transaction.json')
return
def bull_market(self, df, ticker):
m5 = df['close'].rolling(5).mean()
last_m5 = m5[-2]
price = pybithumb.get_current_price(ticker)
if price > last_m5:
return True
return False
def append(self, df, stock):
for i in range(len(df)):
stock['PRICE'].append(
{
"ymd": df.index[i].strftime('%Y.%m.%d'),
"close": df['close'][i],
"diff": 0,
"open": df['open'][i],
"high": df['high'][i],
"low": df['low'][i],
"volume": df['volume'][i],
"avg3": -1,
"avg4": -1,
"avg5": -1,
"avg6": -1,
"avg10": -1,
"avg12": -1,
"avg20": -1,
"avg36": -1,
"avg40": -1,
"avg48": -1,
"avg60": -1,
"avg120": -1,
"avg200": -1,
"avg240": -1,
"avg300": -1,
"disparity_avg5": -1,
"disparity_avg10": -1,
"disparity_avg20": -1,
"disparity_avg60": -1,
"disparity_avg120": -1,
"bolingerband_upper": -1,
"bolingerband_lower": -1,
"bolingerband_middle": -1,
"envelope_upper": -1,
"envelope_lower": -1,
"envelope_middle": -1,
"ichimokucloud_changeLine": -1,
"ichimokucloud_baseLine": -1,
"ichimokucloud_leadingSpan1": -1,
"ichimokucloud_leadingSpan2": -1,
"stochastic_fast_k": -1,
"stochastic_slow_k": -1,
"stochastic_slow_d": -1,
"rsi": -1,
"rsis": -1,
"macd": -1,
"macds": -1,
"macdo": -1,
})
return
def analyze (self, stock, days=120):
stock["PRICE"] = sorted(stock["PRICE"], key=lambda x: x['ymd'])
self.analyzerSqlite.get_moving_average(stock["PRICE"])
# 이동 평균을 이용한 이격도 계산
self.analyzerSqlite.get_disparity(stock["PRICE"])
self.analyzerSqlite.ichimokuCloud.analyze(stock)
self.analyzerSqlite.stochastic.analyze(stock)
self.analyzerSqlite.bolingerBand.analyze(stock)
self.analyzerSqlite.envelope.analyze(stock)
self.analyzerSqlite.rsi.analyze(stock)
self.analyzerSqlite.macd.analyze(stock)
result = {
"ymd": [],
"open": [],
"close": [],
"high": [],
"low": [],
"avg3": [],
"avg4": [],
"avg5": [],
"avg6": [],
"avg10": [],
"avg12": [],
"avg20": [],
"avg36": [],
"avg40": [],
"avg48": [],
"avg60": [],
"avg120": [],
"avg200": [],
"avg240": [],
"avg300": [],
"disparity_avg5": [],
"disparity_avg20": [],
"disparity_avg60": [],
"disparity_avg120": [],
"disparity": [],
"disparity_type": [],
"envelope_upper": [],
"envelope_lower": [],
"envelope_middle": [],
"rsi": [],
"rsis": [],
"macd": [],
"macds": [],
"slow_k": [],
"slow_d": [],
"buy": [],
"sell": [],
}
for item in stock['PRICE']:
result["ymd"].append(item['ymd'])
result["open"].append(item['open'])
result["close"].append(item['close'])
result["high"].append(item['high'])
result["low"].append(item['low'])
result["avg3"].append(item['avg3'])
result["avg4"].append(item['avg4'])
result["avg5"].append(item['avg5'])
result["avg6"].append(item['avg6'])
result["avg10"].append(item['avg10'])
result["avg12"].append(item['avg12'])
result["avg20"].append(item['avg20'])
result["avg36"].append(item['avg36'])
result["avg40"].append(item['avg40'])
result["avg48"].append(item['avg48'])
result["avg60"].append(item['avg60'])
result["avg120"].append(item['avg120'])
result["avg200"].append(item['avg200'])
result["avg240"].append(item['avg240'])
result["avg300"].append(item['avg300'])
result["disparity_avg5"].append(item['disparity_avg5'])
result["disparity_avg20"].append(item['disparity_avg20'])
result["disparity_avg60"].append(item['disparity_avg60'])
result["disparity_avg120"].append(item['disparity_avg120'])
result['disparity'].append(max(item['disparity_avg5'], item['disparity_avg20'], item['disparity_avg60']) - min(item['disparity_avg5'], item['disparity_avg20'], item['disparity_avg60']))
if item['disparity_avg60'] < item['disparity_avg20'] < item['disparity_avg5']:
result['disparity_type'].append(1)
elif item['disparity_avg5'] < item['disparity_avg20'] < item['disparity_avg60']:
result['disparity_type'].append(-1)
else:
result['disparity_type'].append(0)
result["envelope_upper"].append(item['envelope_upper'])
result["envelope_lower"].append(item['envelope_lower'])
result["envelope_middle"].append(item['envelope_middle'])
result["rsi"].append(item['rsi'])
result["rsis"].append(item['rsis'])
result["macd"].append(item['macd'])
result["macds"].append(item['macds'])
result["slow_k"].append(item['stochastic_slow_k'])
result["slow_d"].append(item['stochastic_slow_d'])
result["buy"].append(-1)
result["sell"].append(-1)
data = pd.DataFrame(result)
df_final_time = pd.DatetimeIndex(result['ymd'])
data.index = df_final_time
data = data.astype(
{
'open': 'int',
'high': 'int',
'low': 'int',
'close': 'int',
'avg3': 'float',
'avg4': 'float',
'avg5': 'float',
'avg6': 'float',
'avg10': 'float',
'avg12': 'float',
'avg20': 'float',
'avg36': 'float',
'avg40': 'float',
'avg48': 'float',
'avg60': 'float',
'avg120': 'float',
'avg200': 'float',
'avg240': 'float',
'avg300': 'float',
'disparity_avg5': 'float',
'disparity_avg20': 'float',
'disparity_avg60': 'float',
'disparity_avg120': 'float',
'buy': 'int',
'sell': 'int',
'slow_k': 'float',
'slow_d': 'float',
'macd': 'float',
'macds': 'float',
'envelope_upper': 'float',
'envelope_lower': 'float',
'envelope_middle': 'float',
'rsi': 'float',
'rsis': 'float'
}
)
scaler = StandardScaler()
low_df = pd.DataFrame(data['low'])
low_df.index = [c for c in range(len(low_df))]
low_std = scaler.fit_transform(data['low'].values.reshape(-1, 1))
low_std = pd.DataFrame(low_std, columns=['low_std'])
min_df = pd.DataFrame({'open': data['open'].to_list(), 'close': data['close'].to_list()})
min_df['min_std'] = min_df.min(axis=1)
min_df.index = [c for c in range(len(min_df))]
min_std = scaler.fit_transform(min_df['min_std'].values.reshape(-1, 1))
min_std = pd.DataFrame(min_std, columns=['min_std'])
line_fitter = LinearRegression()
size = len(data["close"])
gradients_low = []
gradients_avg5 = []
gradients_avg20 = []
gradients_avg60 = []
for i in range(size):
coef_low = -999
coef_avg5 = -999
coef_avg20 = -999
coef_avg60 = -999
if i > 0:
l = days if i >= days else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(low_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_low = line_fitter.coef_[0][0]
l = 5 if i >= 5 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg5 = line_fitter.coef_[0][0]
l = 20 if i >= 20 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg20 = line_fitter.coef_[0][0]
l = 60 if i >= 60 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg60 = line_fitter.coef_[0][0]
gradients_low.append(coef_low)
gradients_avg5.append(coef_avg5)
gradients_avg20.append(coef_avg20)
gradients_avg60.append(coef_avg60)
gradients_low_df = pd.DataFrame(gradients_low, columns=['gradients_low'])
gradients_avg5_df = pd.DataFrame(gradients_avg5, columns=['gradients_avg5'])
gradients_avg20_df = pd.DataFrame(gradients_avg20, columns=['gradients_avg20'])
gradients_avg60_df = pd.DataFrame(gradients_avg60, columns=['gradients_avg60'])
gradients_low_df.index = df_final_time
gradients_avg5_df.index = df_final_time
gradients_avg20_df.index = df_final_time
gradients_avg60_df.index = df_final_time
data = data.merge(gradients_low_df, left_index=True, right_index=True)
data = data.merge(gradients_avg5_df, left_index=True, right_index=True)
data = data.merge(gradients_avg20_df, left_index=True, right_index=True)
data = data.merge(gradients_avg60_df, left_index=True, right_index=True)
return data
def writeFile(self, dirName, ticker, data, bsLine, today):
if bsLine is None:
return
# 어제 데이터는 지운다.
buy_line = bsLine['buy']
buy_weight_line = bsLine['buy_weight']
sell_line = bsLine['sell']
buy_size = []
buy_colors = []
for i in range(len(buy_line)):
if buy_line[i] < 0:
buy_colors.append("#ffffff")
buy_line[i] = nan
buy_size.append(0)
else:
buy_colors.append("#B2028C")
buy_size.append(10 + (0.1 * buy_weight_line[i]))
sell_colors = []
for i in range(len(sell_line)):
if sell_line[i] < 0:
sell_colors.append("#ffffff")
sell_line[i] = nan
else:
sell_colors.append("#00ced1")
# 그래프를 설정한다.
buy_check = go.Scatter(x=data['ymd'], y=buy_line, mode='markers', name="buy", marker=dict(size=buy_size, color=buy_colors, line_width=0))
sell_check = go.Scatter(x=data['ymd'], y=sell_line, mode='markers', name="sell", marker=dict(size=14, color=sell_colors, line_width=0))
envelope_upper = go.Scatter(x=data['ymd'], y=data["envelope_upper"], name="upper", line_color='#000000')
envelope_middle = go.Scatter(x=data['ymd'], y=data["envelope_middle"], name="upper", line_color='#927786')
envelope_lower = go.Scatter(x=data['ymd'], y=data["envelope_lower"], name="lower", line_color='#000000')
avg5 = go.Scatter(x=data['ymd'], y=data["avg5"], name="avg5", line_color='#6C2507')
avg20 = go.Scatter(x=data['ymd'], y=data["avg20"], name="avg20", line_color='#f84c43')
avg60 = go.Scatter(x=data['ymd'], y=data["avg60"], name="avg60", line_color='#f89543')
candle_stick = go.Candlestick(x=data['ymd'], open=data['open'], high=data['high'], low=data['low'], close=data['close'], increasing_line_color='red', decreasing_line_color='blue', showlegend=False)
macd_line = go.Scatter(x=data['ymd'], y=data["macd"], line=dict(color='red', width=2), name='macd')
macd_s_line = go.Scatter(x=data['ymd'], y=data["macds"], line=dict(dash='dashdot', color='black', width=2), name='macds')
# fast_k_line = go.Scatter(x=hts['date'], y=hts["fast_k"], mode='lines', name='fast_k')
slow_k_line = go.Scatter(x=data['ymd'], y=data["slow_k"], line=dict(color='red', width=2), name='slow_k')
slow_d_line = go.Scatter(x=data['ymd'], y=data["slow_d"], line=dict(dash='dashdot', color='black', width=2), name='slow_d')
rsi_line = go.Scatter(x=data['ymd'], y=data["rsi"], line=dict(color='red', width=2), name='rsi')
rsis_line = go.Scatter(x=data['ymd'], y=data["rsis"], line=dict(dash='dashdot', color='black', width=2), name='rsis')
disparity_avg5 = go.Scatter(x=data['ymd'], y=data["disparity_avg5"], name="disparity_avg5", line_color='#8F8203')
disparity_avg20 = go.Scatter(x=data['ymd'], y=data["disparity_avg20"], name="disparity_avg20", line_color='#ff00ff')
disparity_avg60 = go.Scatter(x=data['ymd'], y=data["disparity_avg60"], name="disparity_avg60", line_color='#1469F4')
candle_data = [candle_stick, avg5, avg20, avg60, envelope_upper, envelope_middle, envelope_lower, buy_check, sell_check]
disparity_data = [disparity_avg5, disparity_avg20, disparity_avg60]
macd_data = [macd_line, macd_s_line]
stochastic_data = [slow_k_line, slow_d_line]
rsi_data = [rsi_line, rsis_line]
# 그래프를 그린다.
"""
fig = go.Figure(data=candle_data)
fig.update_layout(title=stock_code + "_" + given_day)
fig.show()
"""
fig = subplots.make_subplots(
rows=5, cols=1,
subplot_titles=("MACD", "RSI", "스토캐스틱", '이격도', '캔들'),
#specs=[[{}], [{}], [{}], [{}], [{}], [{}]],
shared_xaxes=True, horizontal_spacing=0.03, vertical_spacing=0.01,
row_heights=[200, 200, 200, 200, 750]
)
for trace in macd_data:
fig.append_trace(trace, 1, 1)
for trace in rsi_data:
fig.append_trace(trace, 2, 1)
for trace in stochastic_data:
fig.append_trace(trace, 3, 1)
for trace in disparity_data:
fig.append_trace(trace, 4, 1)
for trace in candle_data:
fig.append_trace(trace, 5, 1)
df = pd.DataFrame(bsLine)
df = df.fillna(-1)
buy_count = len(df.loc[df["buy"] > 0])
sell_count = len(df.loc[df["sell"] > 0])
fig.update_layout(height=1700, title="_" + str(buy_count)+","+str(sell_count))
fig['layout'].update()
fileName = "%s/%s_%s.html" % (dirName, ticker, today)
po.write_html(fig, file=fileName, auto_open=False)
return
def getBalance(self, ticker):
tmp = self.bithumb.get_balance(ticker)
return tmp[2]
def buyRealTime(self, ticker, isRealTime=False):
stock = {"CODE": ticker, "NAME": ticker, "PRICE": []}
df = pybithumb.get_ohlcv(ticker)
close = pybithumb.get_current_price(ticker)
size = len(df)
df['close'][size-1] = close
if close < df['low'][size-1]:
df['low'][size - 1] = close
if df['high'][size-1] < close:
df['high'][size - 1] = close
self.append(df, stock)
analyzed_day = 120
data = self.analyze(stock, analyzed_day)
# 분석일 데이터만 활용한다 (이전 데이터는 제거)
data.drop(data.index[:len(data) - analyzed_day], inplace=True)
bsLine, data = self.buySellChecker.checkWithEnvelope(data, analyzed_day, isRealTime=isRealTime)
# 그래프를 그린다.
if len(data.index) > 10:
if not isRealTime:
if max(bsLine['buy'][len(bsLine['buy']) - 2:]) > 100:
balance = self.getBalance(ticker)
count = int(balance * (bsLine['buy_weight'][len(bsLine['buy_weight'])-1]/100))
order = self.bithumb.buy_limit_order(ticker, bsLine['buy'][len(bsLine['buy'])-1], count)
# order: ('bid', 'BTC', 'C0101000000322993432', 'KRW')
with open(self.log_filename, 'a', newline='') as log_file:
wr = csv.writer(log_file)
wr.writerow([datetime.now().strftime('%Y-%m-%d %H:%M:%S'), order[0], order[1], order[2], order[3]])
else:
dirName = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')
self.writeFile(dirName, ticker, data, bsLine, datetime.now().strftime('%Y%m%d %H%M%S'))
return
if __name__ == "__main__":
PROJECT_HOME = os.getcwd()
RESOURCE_PATH = os.path.join(PROJECT_HOME, "resources")
if not os.path.exists(os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')):
os.mkdir(os.path.join(RESOURCE_PATH, 'analysis', 'bithumb'))
dirName = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')
if not os.path.exists(dirName):
os.mkdir(dirName)
bithumb = Bithumb(RESOURCE_PATH)
tickers = ['XRP', 'BTC', 'SOL']
for ticker in tickers:
bithumb.buyRealTime(ticker, isRealTime=False)
print ("done...")

View File

@@ -9,7 +9,6 @@ from hts.OrderType import OrderType
from hts.BuySellChecker import BuySellChecker from hts.BuySellChecker import BuySellChecker
from hts.OrderChecker import OrderChecker from hts.OrderChecker import OrderChecker
from stock.util.LabelChecker import LabelChecker
class HTS_DAILY (HTS): class HTS_DAILY (HTS):
@@ -117,7 +116,7 @@ class HTS_DAILY (HTS):
continue continue
# 분석일 데이터만 활용한다 (이전 데이터는 제거) # 분석일 데이터만 활용한다 (이전 데이터는 제거)
data.drop(data.index[:self.analyzed_day], inplace=True) data.drop(data.index[:len(data) - self.analyzed_day], inplace=True)
bsLine, data = self.buySellChecker.checkTransactionWithEnvelope(data, stock_code, self.analyzed_day, isRealTime=False) bsLine, data = self.buySellChecker.checkTransactionWithEnvelope(data, stock_code, self.analyzed_day, isRealTime=False)

View File

@@ -0,0 +1,83 @@
import pybithumb
con_key = "946dd0b0e6f8ad411144cd33f09518d3" # 본인의 Connect Key를 입력한다.
sec_key = "56b2a3cdd9fe3a82aa3f38c97c161125" # 본인의 Secret Key를 입력한다.
# bithumb api에 연결한 클라스 객체를 선언한다.
bithumb = pybithumb.Bithumb(con_key, sec_key)
def bull_market(ticker):
df = pybithumb.get_ohlcv(ticker)
m5 = df['close'].rolling(5).mean()
last_m5 = m5[-2]
price = pybithumb.get_current_price(ticker)
if price > last_m5:
return True
else:
return False
# 상장된 코인 Tickers 확인하기
#print (bithumb.get_tickers())
tickers = ['XRP']
for ticker in tickers:
# 과거 시세 얻기
result = pybithumb.get_ohlcv(ticker)
print(result)
is_bull = bull_market(ticker)
if is_bull:
print(ticker, "상승장")
else:
print(ticker, "하락장")
# [잔고 확인하기]
# - 비트코인의 총 잔고
# - 거래 중인 비트코인의 수량
# - 보유 중인 총원화
# - 주문에 사용된 원화
# (4.978e-05, 0.0, 3438133.120299, 0)
print (bithumb.get_balance(ticker))
# [매수]
# buy_limit_order() 메서드의 파라미터로 구매하고자 하는 가상화폐의
# 티커, 지정가, 매수 수량을 순서대로 입력합니다
# order = ('bid', 'BTC', 'C0101000000322993432', 'KRW')
order = bithumb.buy_limit_order(ticker, 300, 1)
print(order)
# 미체결 주문 확인
# get_balance를 통해 지정가 주문이 들어간 금액만큼 매수에 사용된 원화의 값이 확인된다. 39098.5에 해당된다.
# (0.04588863, 0.0, 3438133.120299, 39098.5)
print (bithumb.get_balance(ticker))
# 주문 취소 하기
cancel = bithumb.cancel_order(order)
print(cancel) # True
# 호가창 Order Book 살펴보기
orderbook = pybithumb.get_orderbook('BTC')
print (orderbook)
# bids의 최상단 66883000.0원이 매수 최상단 금액 (매수자가 기꺼이 지불하려고 하는 최대 금액)
# asks의 최상단 66919000.0원이 매도 최하단 금액 (판매자가 판매하고자 하는 최소 금액)
"""
{'timestamp': '1616913007272',
'payment_currency': 'KRW',
'order_currency': 'BTC',
'bids': [{'price': 66883000.0, 'quantity': 0.0951},
{'price': 66881000.0, 'quantity': 0.0607},
{'price': 66880000.0, 'quantity': 0.503},
{'price': 66878000.0, 'quantity': 0.0415},
{'price': 66868000.0, 'quantity': 0.0293}],
'asks': [{'price': 66919000.0, 'quantity': 0.9946},
{'price': 66927000.0, 'quantity': 0.002},
{'price': 66936000.0, 'quantity': 0.0382},
{'price': 66937000.0, 'quantity': 0.1541},
{'price': 66939000.0, 'quantity': 0.188}]}
"""

View File

@@ -1108,7 +1108,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
check = True check = True
for l in range(i - 2, i): for l in range(i - 2, i):
@@ -1127,7 +1127,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
check = True check = True
for l in range(i - 6, i): for l in range(i - 6, i):
@@ -1145,7 +1145,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
check = True check = True
for l in range(i - 3, i): for l in range(i - 3, i):
@@ -1163,7 +1163,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
if (data['disparity'][i] < 5 and 99.0 < data['disparity_avg60'][i] < 99.1 and if (data['disparity'][i] < 5 and 99.0 < data['disparity_avg60'][i] < 99.1 and
@@ -1182,7 +1182,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
if data['macd'][i] < -4000: if data['macd'][i] < -4000:
if data['macd'][i-1] < data['macd'][i]: if data['macd'][i-1] < data['macd'][i]:
@@ -1190,7 +1190,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
# macd 이전에 없던 바닥인 경우 상승할 찰나 매수 # macd 이전에 없던 바닥인 경우 상승할 찰나 매수
if data['macds'][i-1] < min(data['macds'][:i-1]): if data['macds'][i-1] < min(data['macds'][:i-1]):
@@ -1199,7 +1199,7 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
if ( if (
98 < data['disparity_avg5'][i] < 100 and data['disparity_avg20'][i] < 93.5 and data['disparity_avg60'][i] < 89 and 98 < data['disparity_avg5'][i] < 100 and data['disparity_avg20'][i] < 93.5 and data['disparity_avg60'][i] < 89 and
@@ -1210,16 +1210,15 @@ class BuySellChecker:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 10 bsLine['buy_weight'][i] = 20
""" if data['slow_k'][i]<20 and data['slow_k'][i-1] < data['slow_d'][i-1] and data['slow_d'][i] < data['slow_k'][i]:
if data['disparity_avg60'][i] < 60:
buy = data['low'][i] buy = data['low'][i]
data['buy'][i] = buy data['buy'][i] = buy
bsLine['buy'][i] = buy bsLine['buy'][i] = buy
bsLine['buy_weight'][i] = 20 bsLine['buy_weight'][i] = 30
"""
return bsLine, data return bsLine, data

View File

@@ -42,9 +42,7 @@ class AnalyzerSqlite:
moving_avg = None moving_avg = None
def __init__(self, stockFileName): def __init__(self, stockFileName=None):
self.stockFileName = stockFileName
self.common = Common() self.common = Common()
self.stochastic = Stochastic() self.stochastic = Stochastic()
@@ -54,6 +52,8 @@ class AnalyzerSqlite:
self.macd = MACD() self.macd = MACD()
self.envelope = Envelope() self.envelope = Envelope()
if stockFileName is not None:
self.stockFileName = stockFileName
self.topCompany = self.getTopCompany(stockFileName, 2000) self.topCompany = self.getTopCompany(stockFileName, 2000)
self.fnguide = self.readFnguide(stockFileName) self.fnguide = self.readFnguide(stockFileName)

View File

@@ -1,8 +1,5 @@
import os.path import os.path
import pandas as pd import pandas as pd
import platform
if platform.system().lower().find("window") >= 0 and platform.architecture()[0] != "64bit" :
import win32com.client
import sqlite3 import sqlite3
import shutil import shutil
@@ -584,7 +581,7 @@ class DailyStatus (HTS):
analyzed_day = 60 analyzed_day = 60
data = self.analyze(stock, analyzed_day) data = self.analyze(stock, analyzed_day)
# 분석일 데이터만 활용한다 (이전 데이터는 제거) # 분석일 데이터만 활용한다 (이전 데이터는 제거)
data.drop(data.index[:analyzed_day], inplace=True) data.drop(data.index[:len(data) - analyzed_day], inplace=True)
# print logs # print logs
for i in range(len(data.index)): for i in range(len(data.index)):
@@ -622,7 +619,7 @@ class DailyStatus (HTS):
stock = self.getLastData(stock_code, n) stock = self.getLastData(stock_code, n)
data = self.analyze(stock, analyzed_day) data = self.analyze(stock, analyzed_day)
# 분석일 데이터만 활용한다 (이전 데이터는 제거) # 분석일 데이터만 활용한다 (이전 데이터는 제거)
data.drop(data.index[:analyzed_day], inplace=True) data.drop(data.index[:len(data) - analyzed_day], inplace=True)
# print logs # print logs
# for i in range(len(data.index)): # for i in range(len(data.index)):
@@ -631,7 +628,6 @@ class DailyStatus (HTS):
bsLine, data = self.buySellChecker.checkTransactionWithEnvelope(data, stock_code, 120, isRealTime=False) bsLine, data = self.buySellChecker.checkTransactionWithEnvelope(data, stock_code, 120, isRealTime=False)
# 그래프를 그린다. # 그래프를 그린다.
if len(data.index) > 10 and bsLine['buy'][len(bsLine['buy'])-1] > 0: if len(data.index) > 10 and bsLine['buy'][len(bsLine['buy'])-1] > 0:
self.writeFile(dailyDirName, stock_code, stock_name, today, data, bsLine) self.writeFile(dailyDirName, stock_code, stock_name, today, data, bsLine)