http://www.hackerschool.org/HS_Boards/zboard.php?id=Free_Board&no=37823 [º¹»ç]
import pyupbit
import numpy as np
import pandas as pd
import time
import datetime
import re
import os
import matplotlib.pyplot as plt
# ³¯Â¥ °¹¼ö Â÷ÀÌ ±¸Çϱâ
def cal_data_different(coin, interval, day_count):
df = pd.read_excel(os.path.join(os.getcwd(),'C:/Users/mark/Desktop/',f"{coin}.xlsx"),index_col=0)
past = datetime.datetime.strptime(str(df.iloc[-1].name), f'%Y-%m-%d %H:%M:00')
now = datetime.datetime.now().strftime(f'%Y-%m-%d %H:%M:00')
now = datetime.datetime.strptime(now, f'%Y-%m-%d %H:%M:00')
diff = str(now-past)
n = re.sub(r'[^0-9]', '', interval, day_count)
h, m, s = list(map(int, diff.split(":")))
total_time_diff = (h * 60) + m + s # ºÐÀ¸·Î ȯ»ê
total_diff_num = int(total_time_diff / int(n))
if "day" in diff: # intervalÀÌ dayÀÌ»ó ³Ñ¾î°¥ °æ¿ì
print("Create new file")
df = pyupbit.get_ohlcv(coin, count=day_count, interval=interval)
time.sleep(0.1)
df = df.drop('value', axis=1)
df = cal_indicators(df)
df.to_excel(excel_writer="C:/Users/mark/Desktop/{coin}.xlsx") # ¿¢¼¿ ÀúÀå
print(f"{coin} Data is saved. . . ")
return df
else:
if total_diff_num > 0: # °»½ÅÀÌ ÇÊ¿äÇÒ°æ¿ì
print('Update Required.') # str(df.iloc[-1,0])
orig_df = df.copy()
dfs = pyupbit.get_ohlcv(coin, count=total_diff_num, interval=interval)
dfs = dfs.drop('value', axis=1)
df = pd.concat([df,dfs], ignore_index=False)
cal_df = cal_indicators(df[-50:])
df = pd.concat([orig_df,cal_df[-total_diff_num:]])
df.to_excel(excel_writer=f'C:/Users/mark/Desktop/{coin}.xlsx')
print(f"Success Update.({coin} update {total_diff_num} amount)")
return df
else: # °»½ÅÀÌ ÇÊ¿ä ¾øÀ» °æ¿ì
print("No update")
return df
# µ¥ÀÌÅÍ ½Ç½Ã°£ ÀúÀåÇϱâ
def save_DataFrame(coin, interval, day_count):
coin = coin # ÄÚÀθí
interval = interval # Â÷Æ®ÀÇ Á¾·ù (minute1,3,5,10,15,30,60), day
day_count = day_count # µ¥ÀÌÅÍ ¼ö
if os.path.exists(os.path.join(os.getcwd(),'C:/Users/mark/Desktop/',f"{coin}.xlsx")): # data°¡ ÀÖÀ» °æ¿ì
print("File exist.")
return cal_data_different(coin, interval, day_count)
else: # data °¡ ¾øÀ» °æ¿ì
print("Create new Dataframe file")
df = pyupbit.get_ohlcv(coin, count=day_count, interval=interval)
time.sleep(0.1)
df = df.drop('value', axis=1)
df = cal_indicators(df)
df.to_excel(excel_writer=f"C:/Users/mark/Desktop/{coin}.xlsx") # ¿¢¼¿ ÀúÀå
print(f"{coin} Data is saved. . . ")
return df
# ÇöÀç°¡ Á¶È¸
def get_current_price(coin):
print(pyupbit.get_current_price(coin))
return pyupbit.get_current_price(coin)
# º¸Á¶ÁöÇ¥ ±¸Çϱâ
def cal_indicators(DataFrame):
df = DataFrame
# Moving Average
df['MA3'] = df['close'].rolling(window=3).mean()
df['MA5'] = df['close'].rolling(window=5).mean()
df['MA10'] = df['close'].rolling(window=10).mean()
df['MA15'] = df['close'].rolling(window=15).mean()
df['MA20'] = df['close'].rolling(window=20).mean() # 20ÀÏ Æò±Õ À̵¿ : Áß°£ º¼¸°Àú ¹êµå
df['MA30'] = df['close'].rolling(window=30).mean()
# RSI
rsi_interval = 14
df['U'] = np.where(df.diff(1)['close'] > 0, df.diff(1)['close'],0)
df['D'] = np.where(df.diff(1)['close'] < 0, df.diff(1)['close']*(-1), 0)
df['AU'] = df['U'].rolling(rsi_interval).mean()
df['AD'] = df['D'].rolling(rsi_interval).mean()
df['RSI'] = (df['AU'] / (df['AU']+df['AD'])) *100
# df['RSI_Signal'] = df['RSI'].rolling(9).mean()
del df['U'], df['D'], df['AU'], df['AD']
# MACD
df['MACD_EMA12'] = df['close'].ewm(span=12).mean()
df['MACD_EMA26'] = df['close'].ewm(span=26).mean()
df['MACD'] = df['MACD_EMA12'] - df['MACD_EMA26']
df['MACD_signal'] = df['MACD'].ewm(span=9).mean()
# Bollinger Band
df['Bollinger_stddev'] = df['close'].rolling(window=20).std() # 20ÀÏ À̵¿ Ç¥ÁØÆíÂ÷
df['Bollinger_upper'] = df['MA20'] + (df['Bollinger_stddev'] * 2) # »ó´Ü º¼¸°Àú ¹êµå
df['Bollinger_lower'] = df['MA20'] - (df['Bollinger_stddev'] * 2) # »ó´Ü º¼¸°Àú ¹êµå
return df
##############################################################################################
if __name__ =="__main__":
pd.set_option('mode.chained_assignment', None) # °æ°í off
print("-----------------------Main-----------------------")
print(f'Stat time : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
# ±âº» ¼ÂÆÃ
start_time = datetime.datetime.now()
coins = pyupbit.get_tickers(fiat="KRW-BTC") # ÄÚÀεé
interval = "day" # Â÷Æ®ÀÇ Á¾·ù (minute1,3,5,10,15,30,60), day
day_count = 365 # Á¶È¸ÇÒ µ¥ÀÌÅÍ ¾ç
# # µ¥ÀÌÅÍ ÀúÀå ȤÀº ºÒ·¯¿À±â, µ¥ÀÌÅÍ °¡°øÇϱâ
while True:
for coin in coins:
df = save_DataFrame(coin,interval,day_count)
time.sleep(1) |
Hit : 172 Date : 2024/09/13 01:40
|