# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 10:52:23 2020

@author: Edouard Machenaud
"""

##############################################################################
#                             IMPORTATIONS
##############################################################################

import pandas as pd
import numpy as np
import os
import glob


# Entrée des devises / Respecter les espaces et les caractères
# Note: la valeur Z en USD associé à 0.9 signifie que
# en EUR, la valeur en euro de Z est : valeur * 0.9
Liste_Devise = [['USD',0.9], ['EUR',1], ['GBP',0.85],['JPY',1.25],['CHF',0.96],['X',0.56]]


# Chemin aux fichiers Positions et Mouvements
#Toujours placer 2 \\ après le C:
path_pos = 'D:\\SAUVEGARDE-23-12-2019\ALOR\Clients\Sanso\Rétrocessions\Position-01-20\Positions' 


# Chemin au listing / Ne pas oublier les deux \\ après le C: dans path_listing
path_listing = 'D:\\SAUVEGARDE-23-12-2019\ALOR\Clients\Sanso\Rétrocessions\Rapports Rétrocession - Automatisation\Fichier Listing Final'


# Chemin d'enregistrement du rapport
# ATTENTION : Le nom du fichier correspond aux caractères entre le dernier \ et le .xlsx
name_save = '\Rapport_trimestriel.xlsx'
path_save = 'D:\\SAUVEGARDE-23-12-2019\ALOR\Clients\Sanso\Rétrocessions\Rapports Rétrocession - Automatisation\Rapports produits\Rapport global Retrocession' + name_save


def report_builder(Liste_Devise,path_pos,path_listing,path_save,name_save):
  
  ##############################################################################
  #                             LECTURE DES FICHIERS POSITIONS et MOUVEMENTS
  ##############################################################################
  # Chemin de tous les fichiers positions
  pos_files = glob.glob(os.path.join(path_pos,'*.xlsx'))

  # Lecture des données Positions
  dataframes_pos = []
  compteur = 0
  for pos_file in pos_files:
    compteur+=1
    if compteur%10==0 or compteur>50:
      print('Nombre de fichiers EXCEL Positions lus : {}'.format(compteur))
    df = pd.read_excel(pos_file)
    dataframes_pos.append(df)

  # Transformation des datasets Positions en Liste pour une meilleure manipulation
  data_pos = []
  for i in range(len(dataframes_pos)):
    data_pos.append(dataframes_pos[i].values)
    
    
  ##############################################################################
  #                             STRUCTURATION DES DONNEES
  ##############################################################################
  
  #Détermination des comptes/ISIN/Dépositaires/Type
    #Uniquement sur les positions, les mouvements ne sont pas utilisés pour réaliser le detail report
  Liste_Compte_ISIN_Depo = []

  for i in range(len(data_pos)):
    for j in range(len(data_pos[i])):
      compte_isin_depot = [data_pos[i][j][1],data_pos[i][j][2],data_pos[i][j][4],data_pos[i][j][9]]
      if compte_isin_depot not in Liste_Compte_ISIN_Depo:
        Liste_Compte_ISIN_Depo.append(compte_isin_depot)

  # Calcul et ajouts des jours du trimestre
  dates = [data_pos[i][0][0] for i in range(len(data_pos))]
  nb_jours_trimestre = (max(dates)-min(dates)).days+1
  nb_jours_actif_trimestre = len(data_pos)

  # Creation des listes utiles
  Valorisation = np.zeros((len(Liste_Compte_ISIN_Depo),nb_jours_actif_trimestre))
  Devise = len(Liste_Compte_ISIN_Depo)*[0]
  Quantite = np.zeros((len(Liste_Compte_ISIN_Depo),nb_jours_actif_trimestre))
  Cours = np.zeros((len(Liste_Compte_ISIN_Depo),nb_jours_actif_trimestre))
  
  ##############################################################################
  #                             CALCUL DES VALORISATIONS et JOURS DETENUS PAR COmpte/ISIN/DEPO
  ##############################################################################


  # Parcours des jours
  for l in range(len(data_pos)):
    print('Jour n°{} traité'.format(l+1))
    # Parcours des titres du jour numéro 'l+1' sachant que l commence à 0
    for k in range(len(data_pos[l])): 
      # Pour un titre, 
      # s'il est présent dans la Liste de tous les titres du trimestre (Liste_Compte_ISIN_Depo),
      # alors la valorisation, la quantite et le cours du titre sera comptabilisé sur la journée étudiée
      for i in range(len(Liste_Compte_ISIN_Depo)): # On essaye de trouver un match entre une position et les comptes/ISIN/Depo existants
        compte_mouvement = [data_pos[l][k][1],data_pos[l][k][2],data_pos[l][k][4],data_pos[l][k][9]]
        if Liste_Compte_ISIN_Depo[i]== compte_mouvement:
          Valorisation[i][l] = data_pos[l][k][6]
          Devise[i] = data_pos[l][k][7]
          Quantite[i][l] = data_pos[l][k][5] 
          Cours[i][l] = data_pos[l][k][8]
  
          break
  print('Recherche des titres DONE')


  New_Valorisation = np.zeros((len(Valorisation),nb_jours_trimestre))
  New_Quantite = np.zeros((len(Valorisation),nb_jours_trimestre))
  # Fonction qui augmente les listes Valorisation et Quantite dans le but 
  # de rajouter jours fériés et week-end  
  for i in range(len(Valorisation)):

    valorisation_list = []
    quantite_list = []
   
    # gerer tous les jours sauf le dernier
    for j in range(len(dates)-1):
      delta_days = (dates[j+1]-dates[j]).days
      for k in range(delta_days):
        valorisation_list.append(Valorisation[i][j])
        quantite_list.append(Quantite[i][j])
        
    # gerer le dernier jour
    valorisation_list.append(Valorisation[i][-1])
    quantite_list.append(Quantite[i][-1])
    
    New_Valorisation[i] = valorisation_list
    New_Quantite[i] = quantite_list
    
    
  # Attribut des nouvelles valeurs Valorisation et Quantite
  Valorisation = New_Valorisation
  Quantite = New_Quantite
 

  # Calcul et Ajout de Holding Days
  # Pour chaque compte/ISIN/depo     
  holding_days_liste = []
  for i in range(len(Liste_Compte_ISIN_Depo)):
    holding_days = 0
    for j in range(len(Valorisation[i])):
      if Valorisation[i][j]!=0:
        holding_days+=1
    holding_days_liste.append(holding_days)
  print('Calcul des holding days DONE')
  
#  # Calcul et Ajout de Holding Days
#  # Pour chaque compte/ISIN/depo
#  holding_days_liste = []
#  for i in range(len(Liste_Compte_ISIN_Depo)):
#    holding_days = 0
#    if Valorisation[i][0]!=0:
#      holding_days+=1
#    for l in range(len(Valorisation[i])-1):
#      delta = dates[l+1] - dates[l]  
#      if Valorisation[i][l+1]!=0:
#        holding_days+= delta.days
#    holding_days_liste.append(holding_days)
#  print('Calcul des holding days DONE')
  
  
  # Calcul de l'Encours Moyen du Fond
  for i in range(len(Liste_Compte_ISIN_Depo)):
    Encours_moyen_du_fond = np.sum(Valorisation[i])/holding_days_liste[i]
    Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [round(Encours_moyen_du_fond,2)]
  print('Calcul Average Market Value DONE')
    
  # Ajout du nombre de la Devise et Jours Détenus
  for i in range(len(Liste_Compte_ISIN_Depo)):
    Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [Devise[i],holding_days_liste[i]]
    
  ##############################################################################
  #                             AJOUT DES FRAIS DE GESTION ET RETRO EN BP
  ##############################################################################


  file_listing = glob.glob(os.path.join(path_listing,'*.xlsx'))

  # Lecture du fichier Listing
  df_listing = pd.read_excel(file_listing[0])

  # Transformation du dataset en liste de valeurs
  data_listing = df_listing.values


  # Ajout des Informations contenues dans le fichier listing
  for i in range(len(Liste_Compte_ISIN_Depo)):
    for j in range(len(data_listing)):
      if Liste_Compte_ISIN_Depo[i][2] == data_listing[j][2]:
        Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [data_listing[j][0],data_listing[j][1],data_listing[j][4],round(data_listing[j][5],2)]
  print('Ajout Info du Listing DONE')
  
  
  ##############################################################################
  #                             CALCUL DES RETRO
  ##############################################################################

  # Calcul des retrocessions en devise
  for i in range(len(Liste_Compte_ISIN_Depo)):
    # Encours moyen * (Jours detenus week end compris / Jours dans le trimestre week end compris) * (Taux de Retro BP * 0.0001) * (Taux de possession annuel)
    # Taux de retro BP : 165 corresponds à 1,65 % = 0.0165 = 165 * 0.0001
#    Retro_devise = Liste_Compte_ISIN_Depo[i][4] * (Liste_Compte_ISIN_Depo[i][6] / nb_jours_trimestre) * (Liste_Compte_ISIN_Depo[i][10]*0.0001) * (Liste_Compte_ISIN_Depo[i][6]/365)

    # Encours moyen * (Taux de Retro BP * 0.0001) * (Taux de possession annuel)
    # Taux de retro BP : 165 corresponds à 1,65 % = 0.0165 = 165 * 0.0001
    Retro_devise = Liste_Compte_ISIN_Depo[i][4] * (Liste_Compte_ISIN_Depo[i][10]*0.0001) * (Liste_Compte_ISIN_Depo[i][6]/365)
    Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [round(Retro_devise,2)]
  print('Calcul Retro en devise DONE')
  
  # Ajout de l'exchange rate
  for i in range(len(Liste_Compte_ISIN_Depo)):
    for j in range(len(Liste_Devise)):
      if Liste_Compte_ISIN_Depo[i][5] == Liste_Devise[j][0]:
        Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [Liste_Devise[j][1]]
  print('Ajout Exchange Rate DONE')

  # Calcul des retrocessions en EUR
  for i in range(len(Liste_Compte_ISIN_Depo)):
    Retro_eur = Liste_Compte_ISIN_Depo[i][11] * Liste_Compte_ISIN_Depo[i][12]
    Liste_Compte_ISIN_Depo[i] = Liste_Compte_ISIN_Depo[i] + [round(Retro_eur,2)]
  print('Calcul Retro en EUR DONE')

  ##############################################################################
  #                             MISE EN FORME DU DETAIL REPORT GLOBAL
  ##############################################################################

  # Aggregation de tous les titres dans un tableau
  # Dans ce tableau, Detail_report_all, on peut produire les sous tableaux qui nous interessent
  Detail_report_all = []
  for i in range(len(Liste_Compte_ISIN_Depo)):
    Detail_report_all.append([Liste_Compte_ISIN_Depo[i][0],Liste_Compte_ISIN_Depo[i][1],Liste_Compte_ISIN_Depo[i][7],Liste_Compte_ISIN_Depo[i][8],Liste_Compte_ISIN_Depo[i][2],Liste_Compte_ISIN_Depo[i][3],Liste_Compte_ISIN_Depo[i][4],Liste_Compte_ISIN_Depo[i][5],Liste_Compte_ISIN_Depo[i][6],Liste_Compte_ISIN_Depo[i][9],Liste_Compte_ISIN_Depo[i][10],Liste_Compte_ISIN_Depo[i][11],Liste_Compte_ISIN_Depo[i][12],Liste_Compte_ISIN_Depo[i][13]])
  print("Rapport Total DONE")
  
  ##############################################################################
  ##############################################################################
  #                             PARTIE I : DETAIL REPORT
  ##############################################################################
  ##############################################################################
  
  ##############################################################################
  #                             TABLEAU n°1 : Detail report
  #                       et    TABLEAU n°2 : Zero Rebate 
  ##############################################################################

  # Critère de sélection Detail Report: les titres de type 'ASV' ou 'FONDS' avec un taux de rétro différent de zéro
  # Critère de sélection Zero Rebate : les titres de type 'ASV' ou 'FONDS'  avec un taux de retro égale à 0 OU les titres autres que 'ASV' OU les titres autres que 'FONDS'
  Detail_report = []
  Zero_Rebate = []
  for i in range(len(Detail_report_all)):
    Type = Detail_report_all[i][5]
    Taux_retro = Detail_report_all[i][10]
    
    #Check critère sélection Detail Report
    if (Type == 'ASV' or Type == 'FONDS') and Taux_retro != 0:
      Detail_report.append(Detail_report_all[i])
    
    #Check critère sélection Zero Rebate
    elif (Type == 'ASV' and Taux_retro == 0) or (Type == 'FONDS' and Taux_retro == 0) or (Type !='ASV') or (Type !='FONDS'):
      Zero_Rebate.append(Detail_report_all[i])
  print("Detail Report et Zero Rebate DONE")  

  # Mise en forme Zero Rebate
  Zero_Rebate_Clean = []
  for i in range(len(Zero_Rebate)):
    Zero_Rebate_Clean.append([Zero_Rebate[i][0],Zero_Rebate[i][1],Zero_Rebate[i][2],Zero_Rebate[i][3],Zero_Rebate[i][4],Zero_Rebate[i][6],Zero_Rebate[i][7]])

  ##############################################################################
  #                             TABLEAU n°3 : Summary by account
  ##############################################################################


  # Initialisation
  # DEPOSITAIRE / COMPTE / RETRO
  Summary_by_account = []

  # Parcours de tous les titres
  for i in range(len(Detail_report_all)):
    # Parcours de tous les Depositaires/Ncompte
    # Fixe la taille de Summary_by_account
    k = len(Summary_by_account)
    Type = Detail_report_all[i][5]
    compteur = 0
    for j in range(k):
      # compteur permet de comptabiliser le nombre d'occurences du doublon Depositaire/N°compte
      if Detail_report_all[i][1] == Summary_by_account[j][0] and Detail_report_all[i][0] == Summary_by_account[j][1] and (Type=='ASV' or Type=='FONDS'):
        #####
        # ATTENTION: TRES PETITE VALEUR NON PRISE EN COMPTE : lorsque la valorisation est très proche de 0, l'encours l'est également
        #####
        Summary_by_account[j][2] = Summary_by_account[j][2] + Detail_report_all[i][13]
        compteur+=1
    
    if compteur==0 and (Type=='ASV' or Type=='FONDS'):
      #####
      # ATTENTION: TRES PETITE VALEUR NON PRISE EN COMPTE avec l'encours nan
      #####
      Summary_by_account.append([Detail_report_all[i][1],Detail_report_all[i][0],Detail_report_all[i][13]])
  print("Summary By Account DONE")


  ##############################################################################
  #                             TABLEAU n°4 : Summary by fund company
  ##############################################################################

  #Initialisation
  Summary_by_fund_comp = []

  # Parcours de tous les titres
  for i in range(len(Detail_report_all)):
    # Parcours de tous les fund_comp
    # Fixe la taille de Summary_by_fund_comp
    k = len(Summary_by_fund_comp)
    Type = Detail_report_all[i][5]
    compteur = 0
    for j in range(k):
      #idem compteur que summary_by_account
      if Detail_report_all[i][2] == Summary_by_fund_comp[j][0] and (Type=='ASV' or Type=='FONDS'):
        compteur+=1
        Summary_by_fund_comp[j][1] = Summary_by_fund_comp[j][1] + Detail_report_all[i][13]
  
    if compteur ==0 and (Type=='ASV' or Type=='FONDS'):
      #idem summary_by_account
      Summary_by_fund_comp.append([Detail_report_all[i][2],Detail_report_all[i][13]])  
      
  print("Summary By Fund Company DONE")      

  ##############################################################################
  #                             MISE EN FORME SOUS EXCEL
  ##############################################################################
  
  # Nom des colonnes dans les pages du fichier excel
  Nom_colonne_detail_report = ['N° Compte','Dépositaire','Société de gestion','Nom Fond','ISIN','Type','Encours Moyen du Fond','Devise','Jours Détenus','BP - Frais de Gestion','BP - Taux Rétro','Rétro en Devise','Taux de change','Rétro en Euros']
  Nom_colonne_Zero_Rebate = ['N° Compte','Dépositaire','Société de gestion','Nom Fond','ISIN','Encours Moyen du Fond','Devise']
  Nom_colonne_Sommaire_par_compte = ['Depositaire','N° Compte','Rétrocession en EUR']
  Nom_colonne_Sommaire_par_compagnie = ['Nom Entreprise','Rétrocession en EUR']

  # Creation des DataFrame
  df_detail_report = pd.DataFrame(Detail_report,columns=Nom_colonne_detail_report)
  df_zero_rebate = pd.DataFrame(Zero_Rebate_Clean,columns=Nom_colonne_Zero_Rebate)
  df_sommaire_par_compte = pd.DataFrame(Summary_by_account,columns=Nom_colonne_Sommaire_par_compte)
  df_sommaire_par_compagnie = pd.DataFrame(Summary_by_fund_comp,columns=Nom_colonne_Sommaire_par_compagnie)

  with pd.ExcelWriter(path_save) as writer:
    df_detail_report.to_excel(writer, sheet_name='Non-Zero Retro')
    df_zero_rebate.to_excel(writer, sheet_name='Zero Retro')
    df_sommaire_par_compte.to_excel(writer, sheet_name='Sommaire par compte')
    df_sommaire_par_compagnie.to_excel(writer, sheet_name='Sommaire par entreprise')

  ##############################################################################
  #                             MISE EN FORME SOUS EXCEL - CHECK
  ##############################################################################
#  
#  df_detail_report_all = pd.DataFrame(Detail_report_all,columns=Nom_colonne_detail_report)
#  df_detail_report_all.to_excel('Detail Report All.xlsx')

  return('Trimestrial Report Done')
  