<jupyter_start><jupyter_text>Aggregation<jupyter_code>def aggregate(Models,num_quarters):
    model_dfs = []
    for model in Models:
        Preds = pd.read_csv('./Labels_and_Preds/Predictions_'+model+'.csv', delimiter = ',', index_col = 'Unnamed: 0')
        model_df = pd.DataFrame()
        for quarter in range(num_quarters):
            Q_portfolio = give_quarter_performance(Preds,Labels,quarter)
            temp_df = pd.DataFrame(Q_portfolio.index)
            model_df = pd.concat([model_df,temp_df], ignore_index= True, axis =1)

        model_dfs.append(model_df)
        
    return model_dfs
Agg_Models = ['Lasso','RF','NN']
Q = aggregate(Agg_Models,8)
'''
0: Lasso
1: NN
2: RF
3: Elastic Net
4: Bagging
5: Ridge
'''
import operator
import itertools

def bootstrap_aggregate(model_outputs):
    Overall_aggregate = []
    num_quarters = model_outputs[0].shape[1]
    for i in range(num_quarters):
        Quarter_aggregate = {}
        for j in range(len(model_outputs)):
            model_portfolio = model_outputs[j][i].values
            for value in model_portfolio:
                value = str(value)
                if value in Quarter_aggregate:
                    Quarter_aggregate[value]+=1
                else:
                    Quarter_aggregate[value] = 1
                    
        Quarter_aggregate_sorted = dict( sorted(Quarter_aggregate.items(), key=operator.itemgetter(1),reverse=True))
        Quarter_aggregate_top_30 = dict(itertools.islice(Quarter_aggregate_sorted.items(), 30))
        Quarter_aggregate_df = pd.DataFrame(list(Quarter_aggregate_top_30.items()))
        Overall_aggregate.append(Quarter_aggregate_df)

    return Overall_aggregate

Overall_bootstrap_agg = bootstrap_aggregate(Q)
def aggregated_performance_top_30(Overall_bootstrap,Labels):
    num_quarters = len(Overall_bootstrap)
    
    total_returns = 100
    q_pers = []
    for quarter in range(num_quarters):
        assets = Overall_bootstrap[quarter][0].values
        q_performance = 0
        asset_labels = Labels[str(quarter)]
        
        for asset in assets:
            asset_performance = asset_labels.loc[(asset)] 
            q_performance = q_performance + 1 + asset_performance
            q_per = ((q_performance-30)/30)*100
        
        total_returns = total_returns * (1+(q_per/100))
        
        print('Quarter '+str(quarter+1)+' Result :' +str("%.2f" % q_per)+' %')
        q_pers.append(q_per)
        
#     compounded_result = total_returns-100
#     q_avg_return = pow(total_returns/100, 1/num_quarters) - 1
#     CAGR = pow(total_returns/100, 1/(num_quarters/4)) - 1
    
#     print('Compounded Result :'+str(compounded_result)+str(' %'))
#     print('Quarterly Compounded Growth Rate :', q_avg_return*100, '%')
#     print('Annual Compounded Growth Rate :', CAGR*100, '%')
#     print('Sharpe Ratio :', pow(q_avg_return*100/np.std(q_pers),1/4))
    
    compounded_result = total_returns-100
    q_avg_return = (pow(total_returns/100, 1/num_quarters) - 1) * 100
    CAGR = (pow(total_returns/100, 1/(num_quarters/4)) - 1) * 100
    
    print('Compounded Result :'+str("%.2f" % compounded_result)+str(' %'))
    print('Quarterly Compounded Growth Rate :',"%.2f" % q_avg_return, '%')
    print('CAGR :',"%.2f" %  CAGR, '%')
    print('Sharpe Ratio :',"%.2f" % (4**0.5 * (q_avg_return/np.std(q_pers))))  
    
    positives = []
    for q_per in q_pers:
        if q_per >0:
            positives.append(True)
        else:
            positives.append(False)
            
    positives = pd.Series(positives)
    
    plt.figure(figsize=(7,5))
    plt.bar(np.arange(1,len(q_pers)+1),q_pers,color=positives.map({True: 'g', False: 'r'}),width = 0.5)
    plt.axhline(0,color='black')
    plt.ylabel('Performance in Percentage')
    plt.xlabel('Quarters')
    plt.title('Portfolio Performance of Aggregated model')
    plt.show()
aggregated_performance_top_30(Overall_bootstrap_agg,Labels)
# thresholding done
# binarisation done
# denoising - local means, NLM, gaussian - done
# dilation - done
# erosion - done
# segmentation 
# brightness 
# contrast 
# histogram equalization - done
# linear stretching<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12712066905615294, 'fraction_numerical': 0.024611708482676225, 'mean_word_length': 3.068027210884354, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '60614', 'license': 'MIT', 'n_tokens_mistral': 1500, 'n_tokens_neox': 1375, 'n_words': 244, 'path': '.ipynb_checkpoints/009_Aggregation _and_Results-checkpoint.ipynb', 'repo_name': 'dxcv/Portfolio-Management', 'size': '4185'}