
from base_class import BaseVariableFunction
from base_class import *
baseclass = BaseVariableFunction(__file__)

old_print = print
 

def timestamped_print(*args, **kwargs):
    old_print(datetime.datetime.utcnow().replace(
        microsecond=0), *args, **kwargs)

 

print = timestamped_print
print('\n'*5)
print(f"{'{:<6}'.format('ENTER')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

baseclass.makedirpath(  baseclass.dalao_pnl_gmgn_path)
baseclass.makedirpath(baseclass.dalao_total_ana_gmgn_path)

def makescreenurl( urlname,urlparam):
    _url = urlname + urlparam
    return '=HYPERLINK("{}","{}")'.format(_url, _url)

def get_ana_data_lastdays( df,    intervaldays=30):
    if len(df) == 0:
        return 0, 0, 0, 0, 0, 0, 0, 0, 0 
 
    lastdf = df[df["last_active"] <=  intervaldays]
    # 去除那些 只有卖没有买的
    # lastdf = lastdf[lastdf['buy_eth'] != 0]
    
    # lastdf=lastdf[lastdf["profit_eth"] !=0] 
        
    # 去除 buy_eth 过小的 < 0.2 eth  
    # lastdf = lastdf[lastdf['buy_eth'] >= 0.05]

    lastdf = lastdf.reset_index(drop=True)
    
    
    if len(lastdf) == 0:
        return 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0,0,0,0,0
    
    lastdf["profit_eth"]  = np.where(
        lastdf['profit_eth'] != 0,
        lastdf['profit_eth'] ,
        lastdf['sell_eth'] - lastdf['buy_eth'],
       
    )

 
    _cost_sum = lastdf['buy_eth'].sum()
    _earn_sum = lastdf['profit_eth'].sum()
    _cost_median = lastdf['buy_eth'].median()
    _cost_mean = lastdf['buy_eth'].mean()
    _earnper = _earn_sum / _cost_sum if _cost_sum != 0 else 999999
    _trans_amount = len(lastdf)
    lastdf['earn_percent'] = np.where(
        lastdf['buy_eth'] != 0,
        lastdf['profit_eth'] / lastdf['buy_eth'],
        999999,
    )
    earn_per_neg100_neg50 = len( lastdf[ (lastdf["earn_percent"] >=-1) & (lastdf["earn_percent"] <=-0.5 )] )
    earn_per_neg50_pos0 = len( lastdf[ (lastdf["earn_percent"] >-0.5)& (lastdf["earn_percent"] <=0)  ] )
    earn_per_pos0_pos100 = len( lastdf[( lastdf["earn_percent"] >0) & (lastdf["earn_percent"] <=1 )  ] )
    earn_per_pos100_posmax = len( lastdf[ lastdf["earn_percent"] >1 ] )
    
    earn_per_pos400_posmax =  len( lastdf[ lastdf["earn_percent"] > 3 ] )
    
    
    earnmain_max = lastdf['profit_eth'].max()
    _earn_difmax_sum = _earn_sum - earnmain_max
    _cost_difmax_sum = _cost_sum - \
        lastdf[lastdf['profit_eth'] == earnmain_max]['buy_eth'].to_list()[0]
    _dif_earnper = (
        _earn_difmax_sum / _cost_difmax_sum if _cost_difmax_sum != 0 else 999999
    )
    
    
    return (
        _cost_sum,
        _earn_sum,
        _earnper,
        _cost_difmax_sum,
        _earn_difmax_sum,
        _dif_earnper,
        _cost_median,
        _cost_mean,
        _trans_amount,
        earn_per_neg100_neg50,
        earn_per_neg50_pos0,
        earn_per_pos0_pos100,
        earn_per_pos100_posmax,
        earn_per_pos400_posmax,
 
    )


  
def main():
    global arr_totalAnalysis
    for str_dalaoaddress_idx in range(0, len(arr_str_dalaoaddress)):
        
        str_dalaoaddress= arr_str_dalaoaddress[str_dalaoaddress_idx]
        print(f"enter str_dalaoaddress= {str_dalaoaddress}")
        if not (baseclass.dalao_pnl_gmgn_path / f"gmgn_pnl_{str_dalaoaddress}.csv").exists():
            continue
        
        cur_df = pd.read_csv( baseclass.dalao_pnl_gmgn_path / f"gmgn_pnl_{str_dalaoaddress}.csv",dtype=object)
        if len(cur_df)==0:
            continue
        
 
        
        cur_df = cur_df.astype({
            "last_active" :  int ,
            "profit_eth" :  float ,
            "profit_percent" :  float ,
            "buy_eth" :  float ,
            "sell_eth" : float  ,
            "30d_txns_buy" :  int ,
            "30d_txns_sell":  int ,
            
        })
                
        cur_df = cur_df[ cur_df["last_active"]<=30].reset_index(drop=True)
        cur_df=cur_df[cur_df["30d_txns_buy"] !=0].reset_index(drop=True)
        # cur_df.to_csv( baseclass.dalao_pnl_gmgn_path / f"gmgn_pnl_{str_dalaoaddress}.csv",index  = False )
        
        if len(cur_df)==0:
            continue
        
        (_07d_cost, _07d_earn, _07d_earnper, _07d_difcost, _07d_difearn, _07d_difper, 
        _07d_costmedian, _07d_costmean,    _07d_trans ,    _07d_earn_per_neg100_neg50,
        _07d_earn_per_neg50_pos0,        _07d_earn_per_pos0_pos100,     
        _07d_earn_per_pos100_posmax,   _07d_earn_per_pos400_posmax  ,   ) = get_ana_data_lastdays( df=cur_df, intervaldays=7)
        
        # (_15d_cost, _15d_earn, _15d_earnper, _15d_difcost, _15d_difearn, _15d_difper, 
        # _15d_costmedian, _15d_costmean,    _15d_trans ,   ) = get_ana_data_lastdays( df=cur_df, intervaldays=15)
        
        (_30d_cost, _30d_earn, _30d_earnper, _30d_difcost, _30d_difearn, _30d_difper, 
        _30d_costmedian, _30d_costmean,    _30d_trans ,   _30d_earn_per_neg100_neg50,
        _30d_earn_per_neg50_pos0,        _30d_earn_per_pos0_pos100,   
        _30d_earn_per_pos100_posmax, _30d_earn_per_pos400_posmax ,  ) = get_ana_data_lastdays( df=cur_df, intervaldays=30)
        
        (_365d_cost, _365d_earn, _365d_earnper, _365d_difcost, _365d_difearn, _365d_difper, 
        _365d_costmedian, _365d_costmean,    _365d_trans ,   _365d_earn_per_neg100_neg50,
        _365d_earn_per_neg50_pos0,        _365d_earn_per_pos0_pos100,   
        _365d_earn_per_pos100_posmax, _365d_earn_per_pos400_posmax ,  ) = get_ana_data_lastdays( df=cur_df, intervaldays=365)
        
        str_url =   f"https://gmgn.ai/sol/address/{str_dalaoaddress}"
        
        arr_one_ana_data = [
            str_dalaoaddress,
           
            '=HYPERLINK("{}","{}")'.format(str_url, str_url),
            "",
    
            _07d_cost,
            _07d_earn,
            _07d_earnper,
            _07d_difcost,
            _07d_difearn,
            _07d_difper,
            _07d_costmedian,
            _07d_costmean,
            _07d_trans,
            _07d_earn_per_neg100_neg50,
            _07d_earn_per_neg50_pos0,
            _07d_earn_per_pos0_pos100,
            _07d_earn_per_pos100_posmax,
           (_07d_earn_per_pos100_posmax -_07d_earn_per_neg100_neg50 ) / _07d_trans if _07d_trans!=0 else 0,
           (_07d_earn_per_pos400_posmax *2 +    _07d_earn_per_pos100_posmax - _07d_earn_per_pos400_posmax  -_07d_earn_per_neg100_neg50  ) / _07d_trans if _07d_trans!=0 else 0,


            _30d_cost,
            _30d_earn,
            _30d_earnper,
            _30d_difcost,
            _30d_difearn,
            _30d_difper,
            _30d_costmedian,
            _30d_costmean,
            _30d_trans,
            _30d_earn_per_neg100_neg50,
            _30d_earn_per_neg50_pos0,
            _30d_earn_per_pos0_pos100,
            _30d_earn_per_pos100_posmax,
            (_30d_earn_per_pos100_posmax -_30d_earn_per_neg100_neg50 )/ _30d_trans if _30d_trans!=0 else 0,
            (_30d_earn_per_pos400_posmax *2 + _30d_earn_per_pos100_posmax - _30d_earn_per_pos400_posmax  -_30d_earn_per_neg100_neg50  ) / _30d_trans if _30d_trans!=0 else 0,


            _365d_cost,
            _365d_earn,
            _365d_earnper,
            _365d_difcost,
            _365d_difearn,
            _365d_difper,
            _365d_costmedian,
            _365d_costmean,
            _365d_trans,
     


        ]
        arr_totalAnalysis.append(arr_one_ana_data)
        if len(arr_totalAnalysis )%50==0:
            save_total_ana_df()


    
TotalAnalysis_columns = [
    "add",
    "url",
    "beizhu",
 

    "07d_cost",
    "07d_earn",
    "07d_earnper",
    "07d_difcost",
    "07d_difearn",
    "07d_difper",
    "07d_costmedian",
    "07d_costmean",
    "07d_trans",
    "07d_earn_per_neg100_neg50",
    "07d_earn_per_neg50_pos0",
    "07d_earn_per_pos0_pos100",
    "07d_earn_per_pos100_posmax",
    "07d_earn_pos_dif",
    "07d_earn_pos_dif_4x",
		
 
    "30d_cost",
    "30d_earn",
    "30d_earnper",
    "30d_difcost",
    "30d_difearn",
    "30d_difper",
    "30d_costmedian",
    "30d_costmean",
    "30d_trans",
    "30d_earn_per_neg100_neg50",
    "30d_earn_per_neg50_pos0",
    "30d_earn_per_pos0_pos100",
    "30d_earn_per_pos100_posmax",
    "30d_earn_pos_dif",
    "30d_earn_pos_dif_4x",
    
    
    "365d_cost",
    "365d_earn",
    "365d_earnper",
    "365d_difcost",
    "365d_difearn",
    "365d_difper",
    "365d_costmedian",
    "365d_costmean",
    "365d_trans",

    
    

]


def save_total_ana_df():
    cur_time = int(time.time())
    # cur_time=cur_time/1000
 
    TotalAnalysis_df = pd.DataFrame(
        data=arr_totalAnalysis, columns=TotalAnalysis_columns
    )

    TotalAnalysis_df = TotalAnalysis_df.round(4)
    TotalAnalysis_df = TotalAnalysis_df.sort_values(by=["add"], ascending=[
        True]).reset_index(drop=True)
 
 
    TotalAnalysis_df.to_excel(
        baseclass.dalao_total_ana_gmgn_path/f"totalana.xlsx", index=False)

         
df =  pd.read_excel( baseclass.dalao_merge_path / f"merge.xlsx", dtype=object)

arr_str_dalaoaddress = df['dalaoaddress'].drop_duplicates().tolist()


arr_totalAnalysis = []
   
main()
save_total_ana_df()
     
    
print(f"{'{:<6}'.format('END')} {baseclass.scriptfilename} ----------------NOTE-----------NOTE---------------")

