
# 获取每一个时间段的top20 持仓，汇总到一个excel表格中
import pandas as pd
import sys
import os
import time

arr_file = []
merged_df = None
def makeurl( url,url_show):
    return '=HYPERLINK("{}","{}")'.format(url,  url_show)

import pytz
def utc_2_shanghaidate(df , utc_time_col ):
# 将字符串转换为UTC时间的datetime对象
    # df[utc_time_col] = pd.to_datetime(df[utc_time_col], utc=True)
    # 定义UTC+8时区
    utc_plus_8 = pytz.timezone('Asia/Shanghai')
    # 转换为UTC+8时间
    df[utc_time_col] = df[utc_time_col].dt.tz_localize('UTC')
    # # 提取时间字符串
    # df['shanghai_date'] = df['shanghai_date'].dt.strftime('%Y-%m-%d %H:%M')
    df[utc_time_col] = df[utc_time_col].dt.tz_convert(utc_plus_8)
    # 提取时间字符串
    df[utc_time_col] = df[utc_time_col].dt.strftime('%Y-%m-%d %H:%M')
    return df


def handle_df_fun():
    
    global arr_file , merged_df 
    for index, file in enumerate(arr_file):
        cur_df =   pd.read_csv(file )
        cur_df =cur_df.astype({
            "trader_number":int,
        })

        if index==0 :
            merged_df = cur_df
            continue

    merged_df["gmgn"] = merged_df.apply(lambda ser: makeurl(
    f"https://gmgn.ai/sol/token/{ser['token_address']}" , "gmgn" ), axis=1)

    merged_df["defined"] = merged_df.apply(lambda ser: makeurl(
     f"https://www.defined.fi/sol/{ser['token_address']}" , "defined" ), axis=1)
    
    merged_df["beizhu"] = None
    merged_df["lasheng_time"] =None

    
    merged_df["min_block_time"] = pd.to_datetime(merged_df["min_block_time"]  )
    merged_df = utc_2_shanghaidate(merged_df, "min_block_time")
    merged_df["create_time"] = pd.to_datetime(merged_df["create_time"]  )
    merged_df = utc_2_shanghaidate(merged_df, "create_time")

    merged_df=merged_df[['token_address', 'trader_number',  'min_block_time', 
     'create_time', 'time_diff',  'lasheng_time',	'gmgn',	'defined'	,'beizhu' ]]

 

    merged_df.to_excel(f'002_buy_sametoken_dune_{int(time.time())}.xlsx', index=False)
    return
 
    

if __name__ == "__main__":
 
 
    arr_file = os.listdir(os.getcwd())
  
    arr_file = [file for file in arr_file if "dune_buy_sametoken_" in file and file.endswith(".csv")]
 
    arr_file.sort()
    print("read file: ",arr_file)
    
    handle_df_fun()
 
    