=7 && $fondo <=100 ) {
$sql10="select b.*
from Cotizaciones b
inner join (select FORMAT(Fecha,'yyyy') as ano,FORMAT(Fecha,'MM') as mes, Max(fecha) as fecha2 from Cotizaciones WHERE Cod_Entidad='$fondo'
group by FORMAT(Fecha,'yyyy'), FORMAT(Fecha,'MM')) agrupado
on b.Fecha=agrupado.Fecha2
WHERE b.Cod_Entidad='$fondo'
order by (b.Fecha) DESC";
$fila=1;
$banderaaa=0;
$stmt = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
if($fila==1) {$fila=$fila+1;} else {
$aaDivisa=$row['Divisa'];
$aaFecha=$row['Fecha']->format("Y-m-d");
$aaFechaano=$row['Fecha']->format("Y");
$aaFechames=$row['Fecha']->format("m");
$aaParticipaciones=$row['Participaciones'];
$aaCotizacion=$row['Cotizacion'];
$aaCotizacionlux=$row['Cotizacionlux'];
$aaPatrimonio=$row['Patrimonio'];
$banderaaa=1;
if ($aaParticipaciones=='') {$aaParticipaciones=0;}
if ($aaPatrimonio=='') {$aaPatrimonio=0;}
}
if ($banderaaa==1) {
$sql111="select findemes from Fin_Mes where findemes='$aaFecha'";
$stmt111 = sqlsrv_query( $conn, $sql111);
while( $row111 = sqlsrv_fetch_array( $stmt111, SQLSRV_FETCH_ASSOC))
{
$coincidencia=$row111['findemes']->format("Y-m-d");
}
if ($coincidencia!=$aaFecha) {
$sql1112="select findemes from Fin_Mes where DATEPART(yy, findemes)='$aaFechaano' and DATEPART(mm, findemes)='$aaFechames'";
$stmt1112 = sqlsrv_query( $conn, $sql1112);
while( $row1112 = sqlsrv_fetch_array( $stmt1112, SQLSRV_FETCH_ASSOC))
{
$coincidencia2=$row1112['findemes']->format("Y-m-d");
$sql112="insert into Cotizaciones (Cod_Entidad,Divisa,Fecha,Participaciones,Cotizacion,Patrimonio,Cotizacionlux) Values ('$fondo','$aaDivisa','$coincidencia2',
'$aaParticipaciones',
'$aaCotizacion',
'$aaPatrimonio',
'$aaCotizacionlux')";
//echo $sql112.'
';
$stmt112 = sqlsrv_query( $conn, $sql112);
}
}
}
}
}
//Base100 fondos LUX
if ($fondo >=7 && $fondo <=100) {
$sql30="select Id, Cod_Entidad, Fecha, Cotizacion, Cotizacionlux from Cotizaciones WHERE Cod_Entidad='$fondo' and Cotizacionlux is null order by Fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2fecha=$row['Fecha']->format("Y-m-d");
$b2cotizacion=$row['Cotizacion'];
$b2id=$row['Id'];
$sql40="select TOP 1 Id, Cod_Entidad, Fecha, Cotizacion, Cotizacionlux from Cotizaciones WHERE Cod_Entidad='$fondo' and Cotizacionlux IS NOT NULL order by Fecha desc";
$stmt40 = sqlsrv_query( $conn, $sql40);
while( $row = sqlsrv_fetch_array( $stmt40, SQLSRV_FETCH_ASSOC))
{
$b1cotizacion=$row['Cotizacion'];
$b1base100=$row['Cotizacionlux'];
}
$diferencia=(($b2cotizacion-$b1cotizacion)/$b1cotizacion);
$base100calculado=(1+$diferencia)* $b1base100;
$sql20="update Cotizaciones set Cotizacionlux=$base100calculado
where Id='$b2id'";
$stmt20 = sqlsrv_query( $conn, $sql20);
}
}
$sql1="select *
from Entidades WHERE id='$fondo'";
$stmt = sqlsrv_query( $conn, $sql1);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$nombrefondocabecera=$row['Nombre_Corto_Fichas'];
$nombrefondocorto=$row['Nombre_Corto'];
$Entidad=$row['Entidad'];
$Tipo=$row['Tipo'];
$ISIN_DGS=$row['ISIN_DGS'];
$NIF=$row['NIF'];
$Divisa=$row['Divisa'];
$Clase=$row['Clase'];
$Cod_Bloomberg=$row['Cod_Bloomberg'];
$Administrador=$row['Administrador'];
$Cod_Externo=$row['Cod_Externo'];
$Gestora=$row['Gestora'];
$Orden=$row['Orden'];
$Fecha_Inicio=$row['Fecha_Inicio']->format("Y-m-d");
//$depositario=$row['Depositario'];
//$Fecha_Inicio_entidad=$row['Fecha_Inicio'];
$Indice_Referencia=$row['Indice_Referencia'];
$Depositarioentidad=$row['Depositario'];
$Estructura_Legal=$row['Estructura_Legal'];
$Pais_Registro=$row['Pais_Registro'];
$Cierre_Fiscal=$row['Cierre_Fiscal'];
$Hora_Corte=$row['Hora_Corte'];
$Valoracion=$row['Valoracion'];
$Comision_Gestion=$row['Comision_Gestion'];
$Otros_Gastos=$row['Otros_Gastos'];
$Riesgo=$row['Riesgo'];
$Subscripcion_Min=$row['Subscripcion_Min'];
$Cod_PP_DGS=$row['Cod_PP_DGS'];
}
//cambio valores fondos de pensiones
if($fondo==8 || $fondo==10) {
$Hora_Corte=$Gestora;
$Gestora=$Administrador;
$Estructura_Legal=$Cod_PP_DGS;
$Pais_Registro=$nombrefondocorto;
$Fecha_Inicio=$ISIN_DGS;
$Hora_Corte=$Gestora;
$ISIN_DGS=$Subscripcion_Min;
}
$sql2="select * from Entidades WHERE id='$Indice_Referencia'";
$stmt2 = sqlsrv_query( $conn, $sql2);
while( $row = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_ASSOC))
{
$nombrebenchmark=$row['Entidad'];
}
$sql2="select *
from Textos WHERE Entidad='$fondo' and Idioma='$idioma'";
$stmt2 = sqlsrv_query( $conn, $sql2);
while( $row = sqlsrv_fetch_array( $stmt2, SQLSRV_FETCH_ASSOC))
{
$Objetivo=$row['Objetivo'];
$Equipo=$row['Equipo'];
$EstrategiaPart1=$row['EstrategiaPart1'];
$EstrategiaPart2=$row['EstrategiaPart2'];
$comisionresultado=$row['comisionresultado'];
$comisionreembolso=$row['comisionreembolso'];
$highwatermark=$row['highwatermark'];
}
if($fondo<=10 || $fondo >=100) {
// Contribución a la rentabilidad arriba
// $sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
// from Pa WHERE average_weight IS NOT NULL and name != '' and isin!='' and contribution_to_return !='' and fondo='$fondo'
// order by orden desc";
$sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
from Pa WHERE average_weight IS NOT NULL and name != '' and isin!='' and contribution_to_return !='' and fondo=
(select id from entidades where cod_externo=
(select CONVERT(varchar,pool) from entidades where id='$fondo'))
order by orden desc";
//echo $sql;
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$isinoriginal=trim($row['isin']);
$sql22="select distinct Alias from Cartera where Codigo_Isin='$isinoriginal' group by Alias";
$stmt22 = sqlsrv_query( $conn, $sql22);
while( $row22 = sqlsrv_fetch_array( $stmt22, SQLSRV_FETCH_ASSOC))
{
if ($row22['Alias'] == null) {
$nombrefondo=$row['name'];
} else {
$nombrefondo=$row22['Alias'];
}
}
$datocontribucionarriba=$datocontribucionarriba.'
'.$nombrefondo.' ●'.number_format((float)round($row['orden'],1), 1, '.', '').'%' .'
';
}
// Contribución a la rentabilidad abajo
// $sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
// from Pa WHERE average_weight IS NOT NULL and name != '' and isin !='' and contribution_to_return !='' and fondo='$fondo'
// order by orden asc";
$sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
from Pa WHERE average_weight IS NOT NULL and name != '' and isin!='' and contribution_to_return !='' and fondo=
(select id from entidades where cod_externo=
(select CONVERT(varchar,pool) from entidades where id='$fondo'))
order by orden asc";
$o=1;
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$isinoriginal=trim($row['isin']);
$sql22="select distinct Alias from Cartera where Codigo_Isin='$isinoriginal' group by Alias";
$stmt22 = sqlsrv_query( $conn, $sql22);
while( $row22 = sqlsrv_fetch_array( $stmt22, SQLSRV_FETCH_ASSOC))
{
if ($row22['Alias'] == null) {
$nombrefondo=$row['name'];
} else {
$nombrefondo=$row22['Alias'];
}
}
if ($o==1) {
$datocontribucionabajo1=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
$o=2;
} else if ($o==2) {
$datocontribucionabajo2=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
$o=3;
} else {
$datocontribucionabajo3=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
}
}
} else {
// Contribución a la rentabilidad arriba LUX
$sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
from Pa WHERE fondo='$fondo'
order by orden desc";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$nombrefondo=substr($row['name'],0,21);
$datocontribucionarriba=$datocontribucionarriba.''.$nombrefondo.' ●'.number_format((float)round($row['orden'],1), 1, '.', '').'%' .'
';
}
// Contribución a la rentabilidad abajo LUX
$sql="select top 3 name,average_weight,isin,CONVERT(decimal(5,2), replace(contribution_to_return,',','.')) as orden
from Pa WHERE fondo='$fondo'
order by orden asc";
$o=1;
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$nombrefondo=substr($row['name'],0,21);
if ($o==1) {
$datocontribucionabajo1=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
$o=2;
} else if ($o==2) {
$datocontribucionabajo2=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
$o=3;
} else {
$datocontribucionabajo3=''.number_format((float)round($row['orden'],1), 1, '.', '').'%'.' ● '.$nombrefondo.'
';
}
}
}
//Activos bajo gestión
$sql="Select TOP 1 * from Cotizaciones c inner join Fin_Mes f on f.findemes=c.Fecha where c.Cod_Entidad='$fondo' order by c.Fecha desc";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$patrimonio=round($row['Patrimonio']/1000000,1);
//echo $patrimonio;
}
//Cotizaciones
if ($fondo <=12 || $fondo >=100) {
$sql10="select c.Fecha, c.Cotizacion from Cotizaciones c inner join Fin_Mes f on f.findemes=c.Fecha WHERE c.Cod_Entidad='$fondo' order by c.Fecha ASC";
$cuenta=0;
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$gmes=$gmes."'".$row['Fecha']->format("M-y")."',";
$gcotizacion=$gcotizacion.$row['Cotizacion'].',';
$cuenta=$cuenta+1;
}
$gmes= substr($gmes,0,-1);
$gcotizacion= substr($gcotizacion,0,-1);
} else {
$sql10="select c.Fecha, c.Cotizacion, c.Cotizacionlux from Cotizaciones c inner join Fin_Mes f on f.findemes=c.Fecha WHERE c.Cod_Entidad='$fondo' order by c.Fecha ASC";
$cuenta=0;
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$gmes=$gmes."'".$row['Fecha']->format("M-y")."',";
$gcotizacion=$gcotizacion.$row['Cotizacionlux'].',';
$cuenta=$cuenta+1;
}
$gmes= substr($gmes,0,-1);
$gcotizacion= substr($gcotizacion,0,-1);
}
//Rentabilidad acumulada
$gcotizacionvalor=explode(",", $gcotizacion);
$glongitudgcotizacionvalor=count($gcotizacionvalor);
$grentabilidad3a='';
$grentabilidad5a='';
$grentabilidad10a='';
$gcotizacionvaloractual=$gcotizacionvalor[$glongitudgcotizacionvalor-1];
$gcotizacionvalor1a=$gcotizacionvalor[$glongitudgcotizacionvalor-13];
$gcotizacionvalor3a=$gcotizacionvalor[$glongitudgcotizacionvalor-37];
$gcotizacionvalor5a=$gcotizacionvalor[$glongitudgcotizacionvalor-61];
$gcotizacionvalor10a=$gcotizacionvalor[$glongitudgcotizacionvalor-121];
$grentabilidad1a=round(((100*($gcotizacionvaloractual-$gcotizacionvalor1a))/$gcotizacionvalor1a),2).'%';
if ($gcotizacionvalor3a!==null) {
$grentabilidad3a=round(((100*($gcotizacionvaloractual-$gcotizacionvalor3a))/$gcotizacionvalor3a),2).'%';} else {$grentabilidad3a='';}
if ($gcotizacionvalor5a!==null) {
$grentabilidad5a=round(((100*($gcotizacionvaloractual-$gcotizacionvalor5a))/$gcotizacionvalor5a),2).'%';} else {$grentabilidad5a='';}
if ($gcotizacionvalor10a!==null) {
$grentabilidad10a=round(((100*($gcotizacionvaloractual-$gcotizacionvalor10a))/$gcotizacionvalor10a),2).'%';} else {$grentabilidad10a='';}
$sql10="select top 1 c.Fecha, c.Cotizacion from Cotizaciones c inner join Fin_Mes f on f.findemes=c.Fecha WHERE c.Cod_Entidad='$fondo' order by c.Fecha DESC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$Ultimodatofecha=$row['Fecha']->format("Y-m-d");
$valorliquidativodato=substr($row['Cotizacion'],0,9);
if($fondo>=13) {
//$valorliquidativodato=substr($row['Cotizacion'],0,7);
$valorliquidativodato=number_format((float)round($row['Cotizacion'],2), 2, '.', '');
}
$mesencurso=date("Y F", strtotime($Ultimodatofecha));
//$mesencursomes=date("F", strtotime($Ultimodatofecha));
$anoencurso=date("y", strtotime($Ultimodatofecha));
$anoencursogrande=date("Y", strtotime($Ultimodatofecha));
}
$sql10="select top 1 cast(Fecha_Valoracion as datetime) as fecha from Cartera c inner join Entidades n on n.Cod_Externo=c.Cartera WHERE n.Id='$fondo' order by Fecha_Valoracion DESC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$Ultimodatofechac=$row['fecha']->format("Y-m-d");
$mesencursoc=date("Y F", strtotime($Ultimodatofechac));
$mesencursomes=date("F", strtotime($Ultimodatofechac));
$anocartera=date("Y", strtotime($Ultimodatofechac));
}
//top 5 posiciones grafica derecha
$sql="select top 5 e.Id, CONVERT(decimal(5,2), replace(c.Peso,',','.')) as orden, c.Alias from Cartera c inner join Entidades e
on e.Cod_Externo=c.Cartera where Id='$fondo' and Instrumento!=0 order by orden desc";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$nombre=$nombre."'".$row['Alias']."',";
$valor=$valor.$row['orden'].',';
}
$nombre= substr($nombre,0,-1);
$valor= substr($valor,0,-1);
// Histórico de rentabilidad
$gmesvalor=explode(",", $gmes);
$glongitudgmesvalor=count($gmesvalor);
$gmesvaloractual=$gmesvalor[$glongitudgmesvalor-1];
//buscamos donde está en el array el mes de diciembre del año anterior, para buscar la clave y llevarla a las cotizaciones
$anoanterior=$anoencurso-1;
$valormenos1ano="'Dec-".$anoanterior."'";
$clave = array_search($valormenos1ano, $gmesvalor);
$cotizacionanoanterior1= $gcotizacionvalor[$clave];
$cotizacionanoanterior2= $gcotizacionvalor[$clave-12];
$cotizacionanoanterior3= $gcotizacionvalor[$clave-24];
$cotizacionanoanterior4= $gcotizacionvalor[$clave-36];
$cotizacionanoanterior5= $gcotizacionvalor[$clave-48];
if ($cotizacionanoanterior2!==null) {
$Rentabilidadanoanterior1=round(((100*($cotizacionanoanterior1-$cotizacionanoanterior2))/$cotizacionanoanterior2),2).'%';
}
if ($cotizacionanoanterior3!==null) {
$Rentabilidadanoanterior2=round(((100*($cotizacionanoanterior2-$cotizacionanoanterior3))/$cotizacionanoanterior3),2).'%';
}
if ($cotizacionanoanterior4!==null) {
$Rentabilidadanoanterior3=round(((100*($cotizacionanoanterior3-$cotizacionanoanterior4))/$cotizacionanoanterior4),2).'%';
}
if ($cotizacionanoanterior5!==null) {
$Rentabilidadanoanterior4=round(((100*($cotizacionanoanterior4-$cotizacionanoanterior5))/$cotizacionanoanterior5),2).'%';
}
function fechaCastellano ($fecha) {
$fecha = substr($fecha, 0, 10);
$numeroDia = date('d', strtotime($fecha));
$dia = date('l', strtotime($fecha));
$mes = date('F', strtotime($fecha));
$anio = date('Y', strtotime($fecha));
$dias_ES = array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");
$dias_EN = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
$nombredia = str_replace($dias_EN, $dias_ES, $dia);
$meses_ES = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$meses_EN = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$nombreMes = str_replace($meses_EN, $meses_ES, $mes);
return $nombreMes." ".$anio;
}
function fechames ($fecha) {
$fecha = substr($fecha, 0, 10);
$numeroDia = date('d', strtotime($fecha));
$dia = date('l', strtotime($fecha));
$mes = date('F', strtotime($fecha));
$anio = date('Y', strtotime($fecha));
$dias_ES = array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");
$dias_EN = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
$nombredia = str_replace($dias_EN, $dias_ES, $dia);
$meses_ES = array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
$meses_EN = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$nombreMes = str_replace($meses_EN, $meses_ES, $mes);
return $nombreMes;
}
// Extraemos información de la tabla de ratios
$sql10="select * from Ratios WHERE Fund='$fondo'";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
//$rrentabilidadinicio=$row['Profitability_Since_Inception'];
//$rrentabilidadano=$row['Profitability_Year'];
$rnav=$row['NAV'];
$raum_mm=$row['AuM_mn'];
$rweight=$row['Weight'];
$rinvested=$row['Invested'];
$rroce=str_replace(',','.',$row['Roce'])*100;
$rfcf=str_replace(',','.',$row['FCF_Yield'])*100;
$rpe=str_replace(',','.',$row['PE']);
$rnetdebt=$row['Netdebt_Ebitda'];
$rstocks=$row['Stocks'];
$rnetcash=$row['Net_Cash'];
$ryear1=$row['Year1'];
$ryear2=$row['Year2'];
$ryear3=$row['Year3'];
$rUpsided=str_replace(',','.',$row['Upsided'])*100;
$var=$row['VAR'];
}
// Posiciones
$sql="select count(1) as total from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo where e.Id='$fondo' and (c.Tipo_Valor='Renta Variable' or c.Tipo_Valor='Renta Fija') ";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$numeroposicionesdato=$row['total'];
}
//Calculo Benchmark
//Recogemos el indice a rellenar y la ultima fecha rellena
$sql10="select TOP 1 Indice, Fecha from Benchmark WHERE Fondo='$fondo' order by Fecha desc";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$bindice=$row['Indice'];
$bfecha=$row['Fecha']->format("Y-m-d");
}
//echo $Indice;
if($fondo !=2670 && $fondo !=2671) {
// Rellenamos las cotizaciones faltantes
$sql20="insert into Benchmark (Fondo,Indice,Fecha,Cotizacion) select '$fondo','$bindice', Fecha, Cotizacion from Cotizaciones
where Fecha > '$bfecha'
and Cod_Entidad ='$bindice' order by Fecha ASC";
$stmt20 = sqlsrv_query( $conn, $sql20);
// Calculamos el base 100
if($fondo !=5 && $fondo!=10) {
$sql30="select Indice, Fecha, Cotizacion, Fondo, Base100, Id from Benchmark WHERE Fondo='$fondo' and Indice='$bindice' and Base100 is null order by Fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2fecha=$row['Fecha']->format("Y-m-d");
$b2cotizacion=$row['Cotizacion'];
$b2id=$row['Id'];
$sql40="select TOP 1 Indice, Fecha, Cotizacion, Base100 from Benchmark WHERE Fondo='$fondo' and Base100 IS NOT NULL order by Fecha desc";
$stmt40 = sqlsrv_query( $conn, $sql40);
while( $row = sqlsrv_fetch_array( $stmt40, SQLSRV_FETCH_ASSOC))
{
$b1cotizacion=$row['Cotizacion'];
$b1base100=$row['Base100'];
}
$diferencia=(($b2cotizacion-$b1cotizacion)/$b1cotizacion);
$base100calculado=(1+$diferencia)* $b1base100;
$sql20="update Benchmark set Base100=$base100calculado
where Id='$b2id'";
$stmt20 = sqlsrv_query( $conn, $sql20);
}
} else {
if($fondo ==5) {
$sql20="insert into calculo_benchmark_renta (Fondo,Indice,Fecha,Cotizacion) select b.Fondo,b.Indice,b.Fecha,b.Cotizacion from Benchmark b
left join calculo_benchmark_renta r on b.Fondo=r.Fondo and b.Fecha=r.Fecha
where b.Base100 is NULL and r.Fecha is null
and b.Fondo=5 order by Fecha ASC";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select Indice, Fecha, Cotizacion, Fondo, Base100, Id from calculo_benchmark_renta WHERE Base100 is null order by Fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$primerid=$row['Id'];
$sql20="select t1.Fecha as fechat1, t2.Fecha as fechat2, t1.Cotizacion as cotizaciont1, t2.Cotizacion as cotizaciont2, t1.Base100 as base100t1, t2.Base100 as base100t2 from calculo_benchmark_renta t1 inner join calculo_benchmark_renta t2
on t1.id = t2.id - 1
where t2.Id='$primerid'";
$stmt20 = sqlsrv_query( $conn, $sql20);
while( $row = sqlsrv_fetch_array( $stmt20, SQLSRV_FETCH_ASSOC))
{
$t1fecha=$row['fechat1']->format("Y-m-d");
$t2fecha=$row['fechat2']->format("Y-m-d");
$t1cotizacion=$row['cotizaciont1'];
$t2cotizacion=$row['cotizaciont2'];
$t1base100=$row['base100t1'];
$t2base100=$row['base100t2'];
$date1 = new DateTime($t2fecha);
$date2 = new DateTime($t1fecha);
$diff = $date1->diff($date2);
$direnciafechasbenchmarkrenta=$diff->days;
$base100calculadorenta=(1+($t1cotizacion*($direnciafechasbenchmarkrenta)/36000))*$t1base100;
$sql="update calculo_benchmark_renta set Base100=$base100calculadorenta where Id=$primerid";
$stmt = sqlsrv_query( $conn, $sql);
}
}
$sql="update b set b.Base100=r.Base100 from Benchmark b inner join calculo_benchmark_renta r on b.Fecha=r.Fecha
where b.Fondo=5 and b.Base100 is null";
$stmt = sqlsrv_query( $conn, $sql);
}
}
} else {
// Rellenamos las cotizaciones faltantes
if($fondo ==2670) {
$sql20="insert into calculo_benchmark_iberia (fecha, igbm) select c.Fecha, c.Cotizacion from Cotizaciones c
left join calculo_benchmark_iberia i on i.fecha=c.Fecha where i.fecha is null and c.Cod_Entidad=72 and c.Fecha >='2017-03-31' order by c.Fecha asc";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update i set i.psi20=c.Cotizacion from calculo_benchmark_iberia i inner join Cotizaciones c on c.Fecha=i.fecha where c.Cod_Entidad=84 and i.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.psi20=t1.psi20 from calculo_benchmark_iberia t1 inner join calculo_benchmark_iberia t2
on t1.id = t2.id - 1
where t2.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vpsi20=(t2.psi20/t1.psi20)-1 from calculo_benchmark_iberia t1 inner join calculo_benchmark_iberia t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vpsi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vigbm=(t2.igbm/t1.igbm)-1 from calculo_benchmark_iberia t1 inner join calculo_benchmark_iberia t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vigbm is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
//$sql20="update calculo_benchmark_iberia set base100=100 where id=854";
//$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select id, fecha, base100 from calculo_benchmark_iberia WHERE base100 is null order by fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2id=$row['id'];
$sql="update t2 set t2.base100=(1+(t2.vpsi20*0.2)+(t2.vigbm*0.8))*t1.base100 from calculo_benchmark_iberia t1 inner join calculo_benchmark_iberia t2
on t1.id = t2.id - 1 where t2.id=$b2id and t2.base100 is null";
$stmt = sqlsrv_query( $conn, $sql);
}
$sql="delete from Benchmark where Fondo=2670";
$stmt = sqlsrv_query( $conn, $sql);
$sql="insert into Benchmark (Fondo,Indice,Fecha,Base100) select 2670,9999, i.fecha, i.base100 from calculo_benchmark_iberia i ";
$stmt = sqlsrv_query( $conn, $sql);
}
if($fondo ==2671) {
$sql20="insert into calculo_benchmark_iberiaD (fecha, igbm) select c.Fecha, c.Cotizacion from Cotizaciones c
left join calculo_benchmark_iberiaD i on i.fecha=c.Fecha where i.fecha is null and c.Cod_Entidad=72 and c.Fecha >='2021-01-08' order by c.Fecha asc";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update i set i.psi20=c.Cotizacion from calculo_benchmark_iberiaD i inner join Cotizaciones c on c.Fecha=i.fecha where c.Cod_Entidad=84 and i.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.psi20=t1.psi20 from calculo_benchmark_iberiaD t1 inner join calculo_benchmark_iberiaD t2
on t1.id = t2.id - 1
where t2.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vpsi20=(t2.psi20/t1.psi20)-1 from calculo_benchmark_iberiaD t1 inner join calculo_benchmark_iberiaD t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vpsi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vigbm=(t2.igbm/t1.igbm)-1 from calculo_benchmark_iberiaD t1 inner join calculo_benchmark_iberiaD t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vigbm is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
//$sql20="update calculo_benchmark_iberia set base100=100 where id=854";
//$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select id, fecha, base100 from calculo_benchmark_iberiaD WHERE base100 is null order by fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2id=$row['id'];
$sql="update t2 set t2.base100=(1+(t2.vpsi20*0.2)+(t2.vigbm*0.8))*t1.base100 from calculo_benchmark_iberiaD t1 inner join calculo_benchmark_iberiaD t2
on t1.id = t2.id - 1 where t2.id=$b2id and t2.base100 is null";
$stmt = sqlsrv_query( $conn, $sql);
}
$sql="delete from Benchmark where Fondo=2671";
$stmt = sqlsrv_query( $conn, $sql);
$sql="insert into Benchmark (Fondo,Indice,Fecha,Base100) select 2671,9999, i.fecha, i.base100 from calculo_benchmark_iberiaD i ";
$stmt = sqlsrv_query( $conn, $sql);
}
}
if($fondo==25) {
$sql20="insert into calculo_benchmark_iberialux (fecha, igbm) select c.Fecha, c.Cotizacion from Cotizaciones c
left join calculo_benchmark_iberialux i on i.fecha=c.Fecha where i.fecha is null and c.Cod_Entidad=72 and c.Fecha >='2019-10-11' order by c.Fecha asc";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update i set i.psi20=c.Cotizacion from calculo_benchmark_iberialux i inner join Cotizaciones c on c.Fecha=i.fecha where c.Cod_Entidad=84 and i.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.psi20=t1.psi20 from calculo_benchmark_iberialux t1 inner join calculo_benchmark_iberialux t2
on t1.id = t2.id - 1
where t2.psi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vpsi20=(t2.psi20/t1.psi20)-1 from calculo_benchmark_iberialux t1 inner join calculo_benchmark_iberialux t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vpsi20 is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.vigbm=(t2.igbm/t1.igbm)-1 from calculo_benchmark_iberialux t1 inner join calculo_benchmark_iberialux t2
on t1.id = t2.id - 1
where t1.id>=0 and t2.vigbm is null";
$stmt20 = sqlsrv_query( $conn, $sql20);
//$sql20="update calculo_benchmark_iberia set base100=100 where id=854";
//$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select id, fecha, base100 from calculo_benchmark_iberialux WHERE base100 is null order by fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2id=$row['id'];
$sql="update t2 set t2.base100=(1+(t2.vpsi20*0.2)+(t2.vigbm*0.8))*t1.base100 from calculo_benchmark_iberialux t1 inner join calculo_benchmark_iberialux t2
on t1.id = t2.id - 1 where t2.id=$b2id and t2.base100 is null";
$stmt = sqlsrv_query( $conn, $sql);
}
$sql="delete from Benchmark where Fondo=25";
$stmt = sqlsrv_query( $conn, $sql);
$sql="insert into Benchmark (Fondo,Indice,Fecha,Base100) select 25,9999, i.fecha, i.base100 from calculo_benchmark_iberialux i ";
$stmt = sqlsrv_query( $conn, $sql);
}
if($fondo==10){
//$sql20="insert into calculo_benchmark_pp_mixto (Fondo,Indice,Fecha,Cotizacion,Base100) select 10,69,'2017-07-18','-0.3620000000','100'";
//$stmt20 = sqlsrv_query( $conn, $sql20);
/*
truncate table calculo_benchmark_pp_mixto;
truncate table calculo_benchmark_pp_mixto2;
truncate table calculo_benchmark_pp_mixto3;
insert into calculo_benchmark_pp_mixto (Fondo,Indice,Fecha,Cotizacion,Base100) select 10,69,'2017-07-18','-0.3620000000','100'
insert into calculo_benchmark_pp_mixto2 (Fondo,Indice,Fecha,Cotizacion,Base100) select 10,76, '2017-07-18','211.13','100'
insert into calculo_benchmark_pp_mixto3 (Fondo,Fecha,Base100) select 10, '2017-07-18',100;
*/
$sql20="insert into calculo_benchmark_pp_mixto (Fondo,Indice,Fecha,Cotizacion) select b.Fondo,b.Indice,b.Fecha,b.Cotizacion from Benchmark b
left join calculo_benchmark_pp_mixto r on b.Fondo=r.Fondo and b.Fecha=r.Fecha
where b.Base100 is NULL and r.Fecha is null
and b.Fondo=10 order by Fecha ASC";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select Indice, Fecha, Cotizacion, Fondo, Base100, Id from calculo_benchmark_pp_mixto WHERE Base100 is null order by Fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$primerid=$row['Id'];
$sql20="select t1.Fecha as fechat1, t2.Fecha as fechat2, t1.Cotizacion as cotizaciont1, t2.Cotizacion as cotizaciont2, t1.Base100 as base100t1, t2.Base100 as base100t2 from calculo_benchmark_pp_mixto t1 inner join calculo_benchmark_pp_mixto t2
on t1.id = t2.id - 1
where t2.Id='$primerid'";
$stmt20 = sqlsrv_query( $conn, $sql20);
while( $row = sqlsrv_fetch_array( $stmt20, SQLSRV_FETCH_ASSOC))
{
$t1fecha=$row['fechat1']->format("Y-m-d");
$t2fecha=$row['fechat2']->format("Y-m-d");
$t1cotizacion=$row['cotizaciont1'];
$t2cotizacion=$row['cotizaciont2'];
$t1base100=$row['base100t1'];
$t2base100=$row['base100t2'];
$date1 = new DateTime($t2fecha);
$date2 = new DateTime($t1fecha);
$diff = $date1->diff($date2);
$direnciafechasbenchmarkrenta=$diff->days;
$base100calculadorenta=(1+($t1cotizacion*($direnciafechasbenchmarkrenta)/36000))*$t1base100;
$sql="update calculo_benchmark_pp_mixto set Base100=$base100calculadorenta where Id=$primerid";
$stmt = sqlsrv_query( $conn, $sql);
}
}
//$sql20="insert into calculo_benchmark_pp_mixto2 (Fondo,Indice,Fecha,Cotizacion,Base100) select 10,76, '2017-07-18','211.13','100'";
//$stmt20 = sqlsrv_query( $conn, $sql20);
$sql10="select TOP 1 Indice, Fecha from calculo_benchmark_pp_mixto2 WHERE Fondo='$fondo' order by Fecha desc";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$bindice=$row['Indice'];
$bfecha=$row['Fecha']->format("Y-m-d");
}
$sql20="insert into calculo_benchmark_pp_mixto2 (Fondo,Indice,Fecha,Cotizacion) select '$fondo','$bindice', Fecha, Cotizacion from Cotizaciones
where Fecha > '$bfecha'
and Cod_Entidad ='$bindice' order by Fecha ASC";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql30="select Indice, Fecha, Cotizacion, Fondo, Base100, Id from calculo_benchmark_pp_mixto2 WHERE Fondo='$fondo' and Indice='$bindice' and Base100 is null order by Fecha asc";
$stmt30 = sqlsrv_query( $conn, $sql30);
while( $row = sqlsrv_fetch_array( $stmt30, SQLSRV_FETCH_ASSOC))
{
$b2fecha=$row['Fecha']->format("Y-m-d");
$b2cotizacion=$row['Cotizacion'];
$b2id=$row['Id'];
$sql40="select TOP 1 Indice, Fecha, Cotizacion, Base100 from calculo_benchmark_pp_mixto2 WHERE Fondo='$fondo' and Base100 IS NOT NULL order by Fecha desc";
$stmt40 = sqlsrv_query( $conn, $sql40);
while( $row = sqlsrv_fetch_array( $stmt40, SQLSRV_FETCH_ASSOC))
{
$b1cotizacion=$row['Cotizacion'];
$b1base100=$row['Base100'];
}
$diferencia=(($b2cotizacion-$b1cotizacion)/$b1cotizacion);
$base100calculado=(1+$diferencia)* $b1base100;
$sql20="update calculo_benchmark_pp_mixto2 set Base100=$base100calculado
where Id='$b2id'";
$stmt20 = sqlsrv_query( $conn, $sql20);
}
$sql="insert into calculo_benchmark_pp_mixto3 (Fondo,Fecha,diaria69)
select 10,r2.Fecha, ((r2.Base100/r1.Base100)-1)
from calculo_benchmark_pp_mixto r1
inner join calculo_benchmark_pp_mixto r2 on r1.id = r2.id - 1
left join calculo_benchmark_pp_mixto3 d on d.Fecha=r2.Fecha
where d.Fecha is null
order by r1.Id asc";
$stmt = sqlsrv_query( $conn, $sql);
$sql="update b set b.diaria76=((r2.Base100/r1.Base100)-1)
from calculo_benchmark_pp_mixto2 r1
inner join calculo_benchmark_pp_mixto2 r2 on r1.id = r2.id - 1
inner join calculo_benchmark_pp_mixto3 b on b.Fecha=r2.Fecha";
$stmt = sqlsrv_query( $conn, $sql);
$sql60="select Fecha from calculo_benchmark_pp_mixto3 WHERE Fondo='$fondo' and Base100 is null order by Fecha asc";
$stmt60 = sqlsrv_query( $conn, $sql60);
while( $row = sqlsrv_fetch_array( $stmt60, SQLSRV_FETCH_ASSOC))
{
$fechacalculo=$row['Fecha']->format("Y-m-d");
$sql="update r2 set r2.Base100=(((0.5 * (r2.diaria69 + r2.diaria76))+1) * r1.Base100)
from calculo_benchmark_pp_mixto3 r1
inner join calculo_benchmark_pp_mixto3 r2 on r1.id = r2.id - 1
where r2.Fecha='$fechacalculo'";
$stmt = sqlsrv_query( $conn, $sql);
}
$sql="update b set b.Base100=r.Base100 from Benchmark b inner join calculo_benchmark_pp_mixto3 r on b.Fecha=r.Fecha
where b.Fondo=10 and b.Base100 is null";
$stmt = sqlsrv_query( $conn, $sql);
}
//Cotizaciones Benchmark
$sql10="select b.Fecha, b.Base100 as nbase100
from Benchmark b
inner join (select FORMAT(Fecha,'yyyy') as ano,FORMAT(Fecha,'MM') as mes, Max(fecha) as fecha2 from benchmark WHERE Fondo='$fondo'
group by FORMAT(Fecha,'yyyy'), FORMAT(Fecha,'MM')) agrupado
on b.Fecha=agrupado.Fecha2
WHERE b.Fondo='$fondo'
order by (b.Fecha) ASC";
//$sql10="select c.Fecha, c.Base100 from Benchmark c inner join Fin_Mes f on f.findemes=c.Fecha WHERE c.Fondo='$fondo' order by c.Fecha ASC";
$cuentabenchmark=1;
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
//$gmes=$gmes."'".$row['Fecha']->format("M-y")."',";
if($cuentabenchmark<=$cuenta) {
$bbase100=$bbase100.$row['nbase100'].',';
$cuentabenchmark=$cuentabenchmark+1;
}
}
$bbase100= substr($bbase100,0,-1);
// datos fin de mes
$sql10="select top 1 Fecha
from Benchmark
where Fondo='$fondo'
order by Fecha ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$primerafecha=$row['Fecha']->format("Y-m-d");
}
$sql10="select top 1 Fecha
from datos_cierre_mes
where Fondo='$fondo'
order by Fecha ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$fechadatos=$row['Fecha']->format("Y-m-d");
}
if($primerafecha==$fechadatos) {} else {
$sql10="insert into datos_cierre_mes (Fondo,Fecha,Base100b,Base100) Values('$fondo','$primerafecha', 100, 100)";
$stmt10 = sqlsrv_query( $conn, $sql10);
}
$sql10="insert into datos_cierre_mes (Fondo,Fecha,Base100b) select '$fondo',b.Fecha, b.Base100
from Benchmark b
inner join (select FORMAT(Fecha,'yyyy') as ano,FORMAT(Fecha,'MM') as mes, Max(fecha) as fecha2 from benchmark WHERE Fondo='$fondo'
group by FORMAT(Fecha,'yyyy'), FORMAT(Fecha,'MM')) agrupado
on b.Fecha=agrupado.Fecha2
left join datos_cierre_mes d
on d.Fecha=b.Fecha and d.Fondo='$fondo'
WHERE b.Fondo='$fondo' and b.Fecha<='$Ultimodatofecha' and d.Fecha is null
order by (b.Fecha) ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
if ($fondo<11 || $fondo>=100) {
$sql10="update d set d.Base100=c.Cotizacion from datos_cierre_mes d inner join Cotizaciones c
on c.Fecha=d.Fecha and d.Fondo=c.Cod_Entidad
where d.Fondo='$fondo'";
$stmt10 = sqlsrv_query( $conn, $sql10);
} else {
//calculamos datos de cierre de mes para los fondos de Lux
$sql10="select Fecha
from datos_cierre_mes
where Fondo='$fondo' and Base100 is null
order by Fecha ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$fechadatos=$row['Fecha']->format("Y-m-d");
$fechadatosano=$row['Fecha']->format("Y");
$fechadatosmes=$row['Fecha']->format("m");
$sql110="select top 1 Cotizacionlux
from Cotizaciones
where Cod_Entidad='$fondo' and DATEPART(MM, Fecha)='$fechadatosmes' and DATEPART(YY, Fecha)='$fechadatosano'
order by Fecha DESC";
$stmt110 = sqlsrv_query( $conn, $sql110);
while( $row1 = sqlsrv_fetch_array( $stmt110, SQLSRV_FETCH_ASSOC))
{
$cotizacionlux=$row1['Cotizacionlux'];
}
$sql111="update datos_cierre_mes set Base100='$cotizacionlux' where Fondo='$fondo' and Fecha='$fechadatos'";
$stmt111 = sqlsrv_query( $conn, $sql111);
}
//ponemos la primera fecha con Base100 igual a 100
$sql10="select top 1 Fecha
from datos_cierre_mes
where Fondo='$fondo'
order by Fecha ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$primerafechadatos=$row['Fecha']->format("Y-m-d");
}
$sql111="update datos_cierre_mes set Base100=100 where Fondo='$fondo' and Fecha='$primerafechadatos'";
$stmt111 = sqlsrv_query( $conn, $sql111);
}
$sql20="update t2 set t2.Rentabilidad=((t2.Base100/t1.Base100)-1) from datos_cierre_mes t1 inner join datos_cierre_mes t2
on t1.id = t2.id - 1
where t2.Rentabilidad is null and t2.Fondo='$fondo' and t1.Fondo='$fondo'";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t2 set t2.Rentabilidadb=((t2.Base100b/t1.Base100b)-1) from datos_cierre_mes t1 inner join datos_cierre_mes t2
on t1.id = t2.id - 1
where t2.Rentabilidadb is null and t2.Fondo='$fondo' and t1.Fondo='$fondo'";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="update t set t.dif_Rentabilidad=(t.Rentabilidad-t.Rentabilidadb) from datos_cierre_mes t
where t.Fondo='$fondo'";
$stmt20 = sqlsrv_query( $conn, $sql20);
$sql20="select Fecha, Base100,Rentabilidad from datos_cierre_mes
where Fondo='$fondo' order by Fecha desc";
$stmt20 = sqlsrv_query( $conn, $sql20);
while( $row = sqlsrv_fetch_array( $stmt20, SQLSRV_FETCH_ASSOC))
{
$fecharentabilidades=$fecharentabilidades.$row['Fecha']->format("Y").',';
$rentabilidadesfondo=$rentabilidadesfondo.$row['Rentabilidad'].',';
$rentabilidadbase100=$rentabilidadbase100.$row['Base100'].',';
}
$fecharentabilidades= substr($fecharentabilidades,0,-1);
$rentabilidadesfondo= substr($rentabilidadesfondo,0,-1);
$rentabilidadbase100= substr($rentabilidadbase100,0,-1);
//echo $fecharentabilidades;
$tfecharentabilidades=explode(",", $fecharentabilidades);
$trentabilidadesfondo=explode(",", $rentabilidadesfondo);
$trentabilidadbase100=explode(",", $rentabilidadbase100);
$longitudtrentabilidadesfondo=count($trentabilidadesfondo);
$rentabilidadmescurso=$trentabilidadesfondo[0]*100;
//rentabilidad desde inicio año
for ($i = 0; $i < 13; $i++) {
if ($tfecharentabilidades[$i]==$tfecharentabilidades[0]) {
$trentabilidadesfondoano=$trentabilidadesfondoano+$trentabilidadesfondo[$i];
}
}
$rrentabilidadano=round(($trentabilidadesfondoano*100),2);
//rentabilidad desde inicio
for ($j = 0; $j < $longitudtrentabilidadesfondo; $j++) {
$trentabilidadesfondoinicio=$trentabilidadesfondoinicio+$trentabilidadesfondo[$j];
}
$rrentabilidadinicio=round(($trentabilidadesfondoinicio*100),2);
$rrentabilidadinicio=round(((($trentabilidadbase100[0]/100)-1)*100),2);
if($fondo==7) {
$rrentabilidadinicio=round(((($trentabilidadbase100[0]/1.3989720000)-1)*100),2);
}
// Calculamos la rentabilidad del año
$sql20="select Fecha, Base100,Rentabilidad from datos_cierre_mes
where Fondo='$fondo' order by Fecha desc";
$stmt20 = sqlsrv_query( $conn, $sql20);
$w=0;
$banderaano=0;
while( $row = sqlsrv_fetch_array( $stmt20, SQLSRV_FETCH_ASSOC))
{
if ($w==0) {
$anoencursodato=$row['Fecha']->format("Y");
}
$fechaano=$row['Fecha']->format("Y");
if ($fechaano==$anoencursodato) {
$rentabilidadbase100ano=$rentabilidadbase100ano.$row['Base100'].',';
}
if($banderaano==0){
if ($fechaano!=$anoencursodato) {
$rentabilidadbase100ano=$rentabilidadbase100ano.$row['Base100'].',';
$banderaano=1;
}
}
$w=$w+1;
}
if ($mesencursomes== 'January' || $mesencursomes== 'February' || $mesencursomes== 'March') {$datos='Data as of 1Q '.$anocartera; }
if ($mesencursomes== 'April' || $mesencursomes== 'May' || $mesencursomes== 'June') {$datos='Data as of 2Q '.$anocartera; }
if ($mesencursomes== 'July' || $mesencursomes== 'August' || $mesencursomes== 'September') {$datos='Data as of 3Q '.$anocartera; }
if ($mesencursomes== 'October' || $mesencursomes== 'November' || $mesencursomes== 'December') {$datos='Data as of 4Q '.$anocartera; }
$rentabilidadbase100ano= substr($rentabilidadbase100ano,0,-1);
$drentabilidadbase100ano=explode(",", $rentabilidadbase100ano);
$longitudtrentabilidadbase100ano=count($drentabilidadbase100ano)-1;
$totalenelano= $longitudtrentabilidadbase100ano;
$rrentabilidadano=round((($drentabilidadbase100ano[0]/$drentabilidadbase100ano[$totalenelano])-1)*100,2);
// Calcular distribución historica de rentabilidades
$sql33="select * from Estadisticas WHERE IdFondo='$fondo' and Parametro='Diagrama'";
$stmt33 = sqlsrv_query( $conn, $sql33);
while( $row = sqlsrv_fetch_array( $stmt33, SQLSRV_FETCH_ASSOC))
{
$gdiagrama=$row['Valor'];
}
$l1=0;
$l2=0;
$l3=0;
$l4=0;
$l5=0;
$l6=0;
$l7=0;
$l8=0;
$sql33="select * from datos_cierre_mes WHERE Fondo='$fondo'";
$stmt33 = sqlsrv_query( $conn, $sql33);
while( $row = sqlsrv_fetch_array( $stmt33, SQLSRV_FETCH_ASSOC))
{
$Rentabilidad=$row['Rentabilidad']*100;
switch (true) {
case $Rentabilidad < -7:
$l1+= 1;
break;
case $Rentabilidad >= -7 and $Rentabilidad<-5:
$l2+= 1;
break;
case $Rentabilidad >= -5 and $Rentabilidad<-3:
$l3+= 1;
break;
case $Rentabilidad >= -3 and $Rentabilidad<0:
$l4+= 1;
break;
case $Rentabilidad >= 0 and $Rentabilidad<3:
$l5+= 1;
break;
case $Rentabilidad >= 3 and $Rentabilidad<5:
$l6+= 1;
break;
case $Rentabilidad >= 5 and $Rentabilidad<7:
$l7+= 1;
break;
case $Rentabilidad >= 7:
$l8+= 1;
break;
default:
$l1 = '99999';
break;
}
}
$totaldiagrama=($l1+$l2+$l3+$l4+$l5+$l6+$l7+$l8)/100;
$gdiagrama=$l1/$totaldiagrama.','.$l2/$totaldiagrama.','.$l3/$totaldiagrama.','.$l4/$totaldiagrama.','.$l5/$totaldiagrama.','.$l6/$totaldiagrama.','.$l7/$totaldiagrama.','.$l8/$totaldiagrama;
// recogemos los últimos 13 valores en arrays para acceder a los datos
//ajuste dee estadisticas para coge fondos clase C
if($fondo==2667) {
$fondo=2666;
}
if($fondo==2669) {
$fondo=2668;
}
if($fondo==2671) {
$fondo=2670;
}
if($fondo==2673) {
$fondo=2672;
}
if($fondo==2677) {
$fondo=2676;
}
$sql="select top 13 * from datos_cierre_mes where Fondo='$fondo' order by Fecha desc";
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$ndfechas=$row['Fecha']->format("Y-m-d").",".$ndfechas;
$ndbase100=$row['Base100'].",".$ndbase100;
$ndbase100b=$row['Base100b'].",".$ndbase100b;
$ndrentabilidad=$row['Rentabilidad'].",".$ndrentabilidad;
$ndrentabilidadb=$row['Rentabilidadb'].",".$ndrentabilidadb;
$nddiferencia=$row['dif_Rentabilidad'].",".$nddiferencia;
}
$endfechas=explode(",", $ndfechas);
$longitudendfechas=count($endfechas);
$endbase100=explode(",", $ndbase100);
$longitudendbase100=count($endbase100);
$endbase100b=explode(",", $ndbase100b);
$longitudendbase100b=count($endbase100b);
$endrentabilidad=explode(",", $ndrentabilidad);
$longitudendrentabilidad=count($endrentabilidad);
$endrentabilidadb=explode(",", $ndrentabilidadb);
$longitudendrentabilidadb=count($endrentabilidadb);
$enddiferencia=explode(",", $nddiferencia);
$longitudenddiferencia=count($enddiferencia);
//nuevo cálculo rentabilidad anualizada y la del bechmark
$date1 = new DateTime($endfechas[12]);
$date2 = new DateTime($endfechas[0]);
$diff = $date1->diff($date2);
$direnciafechassrentabilidad=$diff->days;
$dato1rentabilidad=$endbase100[12];
$dato2rentabilidad=$endbase100[0];
$dato1rentabilidadb=$endbase100b[12];
$dato2rentabilidadb=$endbase100b[0];
$RentabilidadAnualizadaFondoValor=round((pow(($dato1rentabilidad/$dato2rentabilidad), (365/$direnciafechassrentabilidad))-1)*100,2);
$RentabilidadAnualizadaBenchmark=round((pow(($dato1rentabilidadb/$dato2rentabilidadb), (365/$direnciafechassrentabilidad))-1)*100,2);
//nuevo cálculo rentabilidad anualizada y la del bechmark
$nsql="select * from datos_cierre_mes where Fondo='$fondo' order by Fecha desc";
$nstmt = sqlsrv_query( $conn, $nsql);
while( $rown = sqlsrv_fetch_array( $nstmt, SQLSRV_FETCH_ASSOC))
{
$ndfechasn=$rown['Fecha']->format("Y-m-d").",".$ndfechasn;
$ndbase100n=$rown['Base100'].",".$ndbase100n;
$ndbase100bn=$rown['Base100b'].",".$ndbase100bn;
$ndrentabilidadn=$rown['Rentabilidad'].",".$ndrentabilidadn;
$ndrentabilidadbn=$rown['Rentabilidadb'].",".$ndrentabilidadbn;
$nddiferencian=$rown['dif_Rentabilidad'].",".$nddiferencian;
}
$nendfechas=explode(",", $ndfechasn);
$nlongitudendfechas=count($nendfechas)-2;
$nendbase100=explode(",", $ndbase100n);
$nlongitudendbase100=count($nendbase100);
$nendbase100b=explode(",", $ndbase100bn);
$nlongitudendbase100b=count($nendbase100b);
$nendrentabilidad=explode(",", $ndrentabilidadn);
$nlongitudendrentabilidad=count($nendrentabilidad);
$nendrentabilidadb=explode(",", $ndrentabilidadbn);
$nlongitudendrentabilidadb=count($nendrentabilidadb);
$nenddiferencia=explode(",", $nddiferencian);
$nlongitudenddiferencia=count($nenddiferencia);
//nuevo cálculo rentabilidad anualizada y la del bechmark
$ndate1 = new DateTime($nendfechas[$nlongitudendfechas]);
$ndate2 = new DateTime($nendfechas[0]);
$ndiff = $ndate1->diff($ndate2);
$ndirenciafechassrentabilidad=$ndiff->days;
$ndato1rentabilidad=$nendbase100[$nlongitudendfechas];
$ndato2rentabilidad=$nendbase100[0];
$ndato1rentabilidadb=$nendbase100b[$nlongitudendfechas];
$ndato2rentabilidadb=$nendbase100b[0];
$nRentabilidadAnualizadaFondoValor=round((pow(($ndato1rentabilidad/$ndato2rentabilidad), (365/$ndirenciafechassrentabilidad))-1)*100,2);
$nRentabilidadAnualizadaBenchmark=round((pow(($ndato1rentabilidadb/$ndato2rentabilidadb), (365/$ndirenciafechassrentabilidad))-1)*100,2);
// echo $nRentabilidadAnualizadaBenchmark;
// nuevo cálculo volatilidad benchmark
$nums = array(
$endrentabilidadb[1],
$endrentabilidadb[2],
$endrentabilidadb[3],
$endrentabilidadb[4],
$endrentabilidadb[5],
$endrentabilidadb[6],
$endrentabilidadb[7],
$endrentabilidadb[8],
$endrentabilidadb[9],
$endrentabilidadb[10],
$endrentabilidadb[11],
$endrentabilidadb[12]
);
//print_r($nums);
$sum=0;
for($i=0;$i $slope,
'intercept' => $intercept,
);
}
$y = array(
$endrentabilidad[1],
$endrentabilidad[2],
$endrentabilidad[3],
$endrentabilidad[4],
$endrentabilidad[5],
$endrentabilidad[6],
$endrentabilidad[7],
$endrentabilidad[8],
$endrentabilidad[9],
$endrentabilidad[10],
$endrentabilidad[11]
);
$x = array(
$endrentabilidadb[1],
$endrentabilidadb[2],
$endrentabilidadb[3],
$endrentabilidadb[4],
$endrentabilidadb[5],
$endrentabilidadb[6],
$endrentabilidadb[7],
$endrentabilidadb[8],
$endrentabilidadb[9],
$endrentabilidadb[10],
$endrentabilidadb[11]
);
$pendiente=linear_regression($x,$y);
//$valorpendiente=explode(",", $pendiente);
$BetaValor=round(($pendiente['slope']),2);
//var_dump($pendiente);
// Alpha
$AlphaValor=round(((((pow(($dato1rentabilidad/$dato2rentabilidad), (365/$direnciafechassrentabilidad))-1)*100)-((pow(($dato1rentabilidadb/$dato2rentabilidadb), (365/$direnciafechassrentabilidad))-1)*100)*$pendiente['slope'])),2);
//Rentabilidad acumulada benchmark
$gcotizacionvalorb=explode(",", $bbase100);
$glongitudgcotizacionvalorb=count($gcotizacionvalorb);
$grentabilidad3ab='';
$grentabilidad5ab='';
$grentabilidad10ab='';
$gcotizacionvaloractualb=$gcotizacionvalorb[$glongitudgcotizacionvalorb-1];
$gcotizacionvalor1ab=$gcotizacionvalorb[$glongitudgcotizacionvalorb-13];
$gcotizacionvalor3ab=$gcotizacionvalorb[$glongitudgcotizacionvalorb-37];
$gcotizacionvalor5ab=$gcotizacionvalorb[$glongitudgcotizacionvalorb-61];
$gcotizacionvalor10ab=$gcotizacionvalorb[$glongitudgcotizacionvalorb-121];
$gcotizacionvalorinicio=$gcotizacionvalorb[0];
$grentabilidad1ab=round(((100*($gcotizacionvaloractualb-$gcotizacionvalor1ab))/$gcotizacionvalor1ab),2).'%';
if ($gcotizacionvalor3a!==null) {
$grentabilidad3ab=round(((100*($gcotizacionvaloractualb-$gcotizacionvalor3ab))/$gcotizacionvalor3ab),2).'%';} else {$grentabilidad3ab='';}
if ($gcotizacionvalor5a!==null) {
$grentabilidad5ab=round(((100*($gcotizacionvaloractualb-$gcotizacionvalor5ab))/$gcotizacionvalor5ab),2).'%';} else {$grentabilidad5ab='';}
if ($gcotizacionvalor10a!==null) {
$grentabilidad10ab=round(((100*($gcotizacionvaloractualb-$gcotizacionvalor10ab))/$gcotizacionvalor10ab),2).'%';} else {$grentabilidad10ab='';}
//$grentabilidaddesdeiniciob=round(((100*($gcotizacionvaloractualb-$gcotizacionvalorinicio))/$gcotizacionvalorinicio),2).'%';
$grentabilidaddesdeiniciob=round(((100*($gcotizacionvaloractualb-100))/100),2).'%';
// Historico rentabilidades Benchmark
$cotizacionanoanterior1b= $gcotizacionvalorb[$clave];
$cotizacionanoanterior2b= $gcotizacionvalorb[$clave-12];
$cotizacionanoanterior3b= $gcotizacionvalorb[$clave-24];
$cotizacionanoanterior4b= $gcotizacionvalorb[$clave-36];
$cotizacionanoanterior5b= $gcotizacionvalorb[$clave-48];
$Rentabilidadanoactualb=round(((100*($gcotizacionvaloractualb-$cotizacionanoanterior1b))/$cotizacionanoanterior1b),2).'%';
if ($cotizacionanoanterior2b!==null) {
$Rentabilidadanoanterior1b=round(((100*($cotizacionanoanterior1b-$cotizacionanoanterior2b))/$cotizacionanoanterior2b),2).'%';
}
if ($cotizacionanoanterior3b!==null) {
$Rentabilidadanoanterior2b=round(((100*($cotizacionanoanterior2b-$cotizacionanoanterior3b))/$cotizacionanoanterior3b),2).'%';
}
if ($cotizacionanoanterior4b!==null) {
$Rentabilidadanoanterior3b=round(((100*($cotizacionanoanterior3b-$cotizacionanoanterior4b))/$cotizacionanoanterior4b),2).'%';
}
if ($cotizacionanoanterior5b!==null) {
$Rentabilidadanoanterior4b=round(((100*($cotizacionanoanterior4b-$cotizacionanoanterior5b))/$cotizacionanoanterior5b),2).'%';
}
if(($fondo==2667 || $fondo==2669 || $fondo==2671 ) && $Rentabilidadanoactualb=='0%') {
$Rentabilidadanoactualb=$grentabilidaddesdeiniciob;
}
//Volvemos a poner el código correcto del fondo
$fondo=$_GET['fondo'];
//ajuste rentabilidad primeros años de los fondos
if ($fondo==2666) {
if($anoencursodato=='2021') {
$Rentabilidadanoanterior5b='6.85%';
$Rentabilidadanoanterior5='-0.19%';
}
}
if ($fondo==2 || $fondo==2668) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='5.94%';
$Rentabilidadanoanterior3='5.75%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='5.94%';
$Rentabilidadanoanterior4='5.75%';
}
}
if ($fondo==3 || $fondo==2670) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='9.01%';
$Rentabilidadanoanterior3='10.19%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='9.01%';
$Rentabilidadanoanterior4='10.19%';
}
}
if ($fondo==4 || $fondo==2672) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='1.69%';
$Rentabilidadanoanterior3='5.81%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='1.69%';
$Rentabilidadanoanterior4='5.81%';
}
}
if ($fondo==5) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='-0.30%';
$Rentabilidadanoanterior3='0.57%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='-0.30%';
$Rentabilidadanoanterior4='0.57%';
}
}
if ($fondo==8) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='2.52%';
$Rentabilidadanoanterior3='1.31%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='2.52%';
$Rentabilidadanoanterior4='1.31%';
}
}
if ($fondo==10) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='1.21%';
$Rentabilidadanoanterior3='1.71%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='1.21%';
$Rentabilidadanoanterior4='1.71%';
}
}
if ($fondo==17) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='0.32%';
$Rentabilidadanoanterior3='5.78%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='0.32%';
$Rentabilidadanoanterior4='5.78%';
}
}
if ($fondo==19) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior3b='0.85%';
$Rentabilidadanoanterior3='6.61%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior4b='0.85%';
$Rentabilidadanoanterior4='6.61%';
}
}
if ($fondo==21) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior2b='-10.36%';
$Rentabilidadanoanterior2='-42.67%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior3b='-10.36%';
$Rentabilidadanoanterior3='-42.67%';
}
if($anoencursodato=='2022') {
$Rentabilidadanoanterior4b='-10.36%';
$Rentabilidadanoanterior4='-42.67%';
}
}
if ($fondo==23) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior2b='-10.36%';
$Rentabilidadanoanterior2='-41.27%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior3b='-10.36%';
$Rentabilidadanoanterior3='-41.27%';
}
if($anoencursodato=='2022') {
$Rentabilidadanoanterior4b='-10.36%';
$Rentabilidadanoanterior4='-41.27%';
}
}
if ($fondo==25) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior1b='4.20%';
$Rentabilidadanoanterior1='8.69%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior2b='4.20%';
$Rentabilidadanoanterior2='8.69%';
}
if($anoencursodato=='2022') {
$Rentabilidadanoanterior3b='4.20%';
$Rentabilidadanoanterior3='8.69%';
}
if($anoencursodato=='2023') {
$Rentabilidadanoanterior4b='4.20%';
$Rentabilidadanoanterior4='8.69%';
}
}
if ($fondo==29) {
if($anoencursodato=='2020') {
$Rentabilidadanoanterior1b='6.71%';
$Rentabilidadanoanterior1='6.51%';
}
if($anoencursodato=='2021') {
$Rentabilidadanoanterior2b='6.71%';
$Rentabilidadanoanterior2='6.51%';
}
if($anoencursodato=='2022') {
$Rentabilidadanoanterior3b='6.71%';
$Rentabilidadanoanterior3='6.51%';
}
if($anoencursodato=='2023') {
$Rentabilidadanoanterior4b='6.71%';
$Rentabilidadanoanterior4='6.51%';
}
}
// Distribución sectorial
if ($idioma=='es') {
$nombrecamposector='s.Nombre_Largo_es';
} else {
$nombrecamposector='s.Nombre_Largo_en';
}
/* if ($fondo==8 || $fondo==10){
$nombrecamposector='s.DGS';
}*/
// $sql10="select distinct top 11 e.Id,$nombrecamposector as nombrelargo, sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma, s.imagenes
// from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
// inner join Sectores s
// on s.Nombre=c.Sector
// where e.Id='$fondo' group by $nombrecamposector, e.ID, s.imagenes
// order by suma desc";
$sql10="select top 11 $nombrecamposector as nombrelargo, sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma, s.imagenes
from Cartera c inner join Entidades e on REPLACE(c.Instrumento, ' ', '')=REPLACE(e.Cod_Externo, ' ', '')
inner join Sectores s
on s.Id=e.Sector
where c.Cartera='$codigocartera' group by e.Sector, c.Cartera,$nombrecamposector, s.imagenes
order by suma desc;";
//echo $sql10;
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$nombresector=$nombresector.$row['nombrelargo'].'|';
$imagenes=$imagenes.$row['imagenes'].'|';
$pesosector=$pesosector.$row['suma'].'|';
$sumasector=$sumasector+$row['suma'];
}
$dnombresector=explode("|", $nombresector);
$dimagenes=explode("|", $imagenes);
$dpesosector=explode("|", $pesosector);
$dotros=number_format((float)round(100-$sumasector,2), 2, '.', '');
// Distribución activos
$sql10="select distinct e.Id,c.Tipo_Valor, sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c
inner join Entidades e
on c.Cartera=e.Cod_Externo
where e.Id='$fondo' and c.Tipo_Valor!='Futuros'
group by c.Tipo_Valor, e.ID ";
$seriesactivos="[";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$seriesactivos=$seriesactivos."{name: '".$row['Tipo_Valor']."',y:".round($row['suma'],1).",
},";
//$tipovalortitulo=$tipovalortitulo.'"'.$row['Tipo_Valor'].'",';
//$tipovalorpeso=$tipovalorpeso.round($row['suma'],1).',';
}
$seriesactivos= substr($seriesactivos,0,-1);
$seriesactivos=$seriesactivos."]";
if ($idioma!=='es') {
$seriesactivos=str_replace('Tesoreria', 'Cash', $seriesactivos);
$seriesactivos=str_replace('Tesorería', 'Cash', $seriesactivos);
$seriesactivos=str_replace('Renta Variable', 'Equity', $seriesactivos);
$seriesactivos=str_replace('Renta Fija', 'Fixed Income', $seriesactivos);
$seriesactivos=str_replace('Activos Monetarios', 'Monetary Assets', $seriesactivos);
}
// echo $tipovalortitulo.'
';
// echo $tipovalorpeso;
// Distribución geográfica
$sql10="select distinct e.Id,agrupado.Continente, sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
inner join (select distinct Continente, Moneda from Divisas
group by Continente, Moneda) agrupado
on c.Divisa=agrupado.Moneda
where e.Id='$fondo'
group by agrupado.Continente, e.ID ";
$valorasia='';
$valorzonaeuro='';
$valorusa='';
$valorrestoeuropa='';
$valorotros='';
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$continente=$row['Continente'];
$valorsuma=round($row['suma'],2);
switch ($continente) {
case 'Asia':
$valorasia=$valorsuma;
break;
case 'Zona Euro':
$valorzonaeuro=$valorsuma;
break;
case 'USA':
$valorusa=$valorsuma;
break;
case 'Resto Europa':
$valorrestoeuropa=$valorsuma;
break;
case 'Otros':
$valorotros=$valorsuma;
break;
default:
break;
}
}
// Calculamos distribución geográfica para el fondo Iberia
if ($fondo==3 || $fondo==25 || $fondo==2670 || $fondo==2671) {
$sql11="select distinct left(c.Codigo_Isin,2) as agrupado,sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
where e.Id=$fondo and c.Sector!='Tesoreria'
group by left(c.Codigo_Isin,2)select distinct left(c.Codigo_Isin,2) as agrupado,sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
where e.Id=$fondo
group by left(c.Codigo_Isin,2)
";
$stmt11 = sqlsrv_query( $conn, $sql11);
while( $row = sqlsrv_fetch_array( $stmt11, SQLSRV_FETCH_ASSOC))
{
$codiberia=$row['agrupado'];
$valoriberia=round($row['suma'],2);
switch ($codiberia) {
case 'ES':
$valorespana=$valoriberia;
break;
case 'PT':
$valorportugal=$valoriberia;
break;
default:
$valoriberiaotros=$valoriberia+$valoriberiaotros;
break;
}
}
$sql11="select distinct sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
where e.Id=2670 and c.Sector='Tesoreria'";
$stmt11 = sqlsrv_query( $conn, $sql11);
while( $row = sqlsrv_fetch_array( $stmt11, SQLSRV_FETCH_ASSOC))
{
$tesoreria=$row['suma'];
}
$valorespana=$valorespana+$tesoreria;
}
// Calculamos la liquidez
$valorliquidez='';
$sql11="select sum(CONVERT(decimal(5,2), replace(c.Peso,',','.'))) as suma
from Cartera c inner join Entidades e on c.Cartera=e.Cod_Externo
where e.Id='$fondo' and c.Sector='Tesoreria'";
$stmt11 = sqlsrv_query( $conn, $sql11);
while( $row = sqlsrv_fetch_array( $stmt11, SQLSRV_FETCH_ASSOC))
{
$valorliquidez=round($row['suma'],2);
}
// $dnombresector=explode(",", $nombresector);
// $dpesosector=explode(",", $pesosector);
// $dotros=number_format((float)round(100-$sumasector,2), 2, '.', '');
function getUrl($navegador) {
$url = preg_replace('/&?fondo=[^&]*/', '', $_SERVER['REQUEST_URI']);
if ($navegador==0) {$fondob=2666;} else {}
if ($navegador==1) {$fondob=2666;} else {}
if ($navegador==2) {$fondob=2667;} else {}
if ($navegador==3) {$fondob=2668;} else {}
if ($navegador==4) {$fondob=2669;} else {}
if ($navegador==5) {$fondob=2670;} else {}
if ($navegador==6) {$fondob=2671;} else {}
if ($navegador==7) {$fondob=2672;} else {}
if ($navegador==8) {$fondob=2673;} else {}
if ($navegador==9) {$fondob=5;} else {}
if ($navegador==10) {$fondob=2676;} else {}
if ($navegador==11) {$fondob=2677;} else {}
if ($navegador==12) {$fondob=7;} else {}
if ($navegador==13) {$fondob=8;} else {}
if ($navegador==14) {$fondob=10;} else {}
if ($navegador==15) {$fondob=13;} else {}
if ($navegador==16) {$fondob=15;} else {}
if ($navegador==17) {$fondob=17;} else {}
if ($navegador==18) {$fondob=19;} else {}
if ($navegador==19) {$fondob=21;} else {}
if ($navegador==20) {$fondob=23;} else {}
if ($navegador==21) {$fondob=25;} else {}
if ($navegador==22) {$fondob=29;} else {}
if ($navegador==23) {$fondob=29;} else {}
/*$sqla11="select * from Entidades where Orden='$navegador'";
$stmta11 = sqlsrv_query( $conn, $sqla11);
while( $rowa = sqlsrv_fetch_array( $stmta11, SQLSRV_FETCH_ASSOC))
{
$fondob=$rowa['Id'];
} */
return $url.'&fondo='.$fondob;
}
function idioma($idioma) {
$url = preg_replace('/&?idioma=[^&]*/', '', $_SERVER['REQUEST_URI']);
return $url.'&idioma='.$idioma;
}
//poner el superíndice en los fondos D
if ($fondo == 2667 || $fondo==2669 || $fondo==2671 || $fondo==2673 || $fondo==2677) {
$d3code='(2)';
} else {
$d3code="";
}
$sup2='(2)';
$sup5='(4)';
$sup6='(5)';
$sup7='(6)';
if ($fondo == 2667 || $fondo==2669 || $fondo==2671 || $fondo==2673 || $fondo==2677) {
$sup2='(3)';
}
if ($idioma=='es') {
$d1="(1) Rentabilidades pasadas no garantizan rentabilidades futuras";
$nombreMes=fechames($Ultimodatofechac);
$comisionresultadotitulo='Comisión de resultado';
$comisionreembolsotitulo='Comisión de reembolso';
$highwatermarktitulo='High Water Mark';
$and='y';
if ($nombreMes== 'Enero' || $nombreMes== 'Febrero' || $nombreMes== 'Marzo') {$datos='Datos de 1T '.$anocartera; }
if ($nombreMes== 'Abril' || $nombreMes== 'Mayo' || $nombreMes== 'Junio') {$datos='Datos de 2T '.$anocartera; }
if ($nombreMes== 'Julio' || $nombreMes== 'Agosto' || $nombreMes== 'Septiembre') {$datos='Datos de 3T '.$anocartera; }
if ($nombreMes== 'Octubre' || $nombreMes== 'Noviembre' || $nombreMes== 'Diciembre') {$datos='Datos de 4T '.$anocartera; }
$notacomision='';
if($fondo==21 || $fondo==23) {$notacomision='La comisión de gestión efectiva cobrada esta reducida al 1.25% (desde Diciembre 2018 y hasta nueva orden)';}
$ratiostitulo="Ratios";
$otrostexto='Otros';
$valorliquidativo='valor liquidativo';
$enelmes='en el mes';
$enelano='en el año';
$desdeelinicio='desde inicio';
$historicorentabilidad='Histórico de rentabilidad (1)';
$vartexto='Pérdida máx. esperada mensual(3)';
$nombrefondo='Fondo';
$diferencia='Diferencia';
$rentabilidadacumulada='Rentabilidad acumulada (1)';
$titulografica1='Rentabilidad fondo vs benchmark';
$contribucionrentabilidad='Contribución a la rentabilidad';
$incrementa='INCREMENTA';
$disminuye='DISMINUYE';
$distribucionhistorica='Distribución histórica de rentabilidades';
$subtitulodistribucion='Porcentaje de meses en los que la rentabilidad se ha situado en el rango';
$subtitulografica1='Crecimiento en euros, base 100';
if ($fondo==15 || $fondo==17 || $fondo==19) {$subtitulografica1='Crecimiento en dólares, base 100';}
$estadisticas='Estadísticas'.$d3code.'
';
$rentabilidadanualizada='Rentabilidad anualizada';
$volatilidad='Volatilidad';
$potencial='Potencial de revalorización'.$sup2.'';
$ano1='1 año';
$ano3='3 años';
$ano5='5 años';
$ano10='10 años';
$indicadorriesgo='Indicador de riesgo';
$top5='Top 5 posiciones';
$menor='Menor';
$entre='Entre';
$mayor='Mayor';
//$datos='Datos de 1S 2019';
$fechadatos=fechaCastellano ($Ultimodatofecha);
$distribuciongeografica='Distribución geográfica';
$usa='Estados
Unidos';
$zonaeuro='Zona Euro';
$restoeuropa='Resto de Europa';
$asia='Asia';
$otros='Otros';
$liquidez='Liquidez';
$espana='España';
$portugal='Portugal';
$distribucionsectorial='Distribución sectorial';
$objetivoinversion='Objetivo de inversión';
$equipogestor='Equipo gestor';
$estrategiainversion='Estrategia y política inversión';
$datosdelfondo='Datos del fondo';
$gestora='Gestora';
$depositario='Depositario';
$estructuralegal='Estructura legal';
$paisregistro='País de registro';
$fechacreacion='Fecha de creación';
$cierreanofilcal='Cierre de año fiscal';
$horacorte='Hora de corte';
$valoraciontitulo='Valoración';
$comisiongestion='Comisión gestión';
$otrosgastos='Otros Gastos Corrientes';
$isin='ISIN';
$codigobloomberg='Código Bloomberg';
$activosbajogestion='Activos bajo gestión';
$numeroposiciones='Número de posiciones';
$contactoinversor='CONTACTO INVERSOR';
$informacionrelevante='Información relevante';
$textopatrimonio=" millones euros";
$distribucionactivos="Distribución activos";
$principalessectores="Principales sectores.";
$contenidodisclaimer='Este documento tiene carácter comercial y se suministra con fines exclusivamente informativos, no pudiendo ser considerado en ningún caso como un elemento contractual, una recomendación, un asesoramiento personalizado o una oferta. Tampoco puede considerarse como sustitutivo de los Datos Fundamentales del Inversor (DFI) o de cualquier otra información legal preceptiva que deberá ser consultada con carácter previo a cualquier decisión de inversión. En caso de discrepancia, la información legal prevalece. Toda esa información legal estará a su disposición en la sede de la Gestora y a través de la página web: www.cobasam.com. Todas las rentabilidades son netas, descontando gastos y comisiones y están denominadas en euros. La inversión en renta variable puede conllevar pérdidas del capital invertido y es desaconsejable para horizontes temporales inferiores a 5 años.';
$d2="
(2) Mejor escenario: Es la diferencia entre el valor objetivo y el precio de mercado agregado de la cartera. Para calcular el valor objetivo, aplicamos un múltiplo al flujo de caja normalizado en base a estimaciones propias de cada compañía.
(3) Peor escenario: Calculado con Metodología VALUE AT RISK (VaR) 2,32 sigmas, nivel de confianza del 99% de la distribución normal a 1 mes.
(4) Se calcula dividiendo la capitalización bursátil de cada compañía entre su flujo de caja normalizado en base a estimaciones propias.
(5) Es el resultado de dividir el flujo de caja normalizado en base a estimaciones propias, entre el Enterprise Value.
(6) Lo calculamos dividiendo el resultado operativo normalizado en base a estimaciones propias, después de impuestos entre el capital empleado (ex - fondo de comercio) para ver la rentabilidad intrínseca del negocio.";
$d3="(2) Al no existir antigüedad suficiente y ser una clase de nueva creación, se utilizan los estadísticos de la clase C";
} else {
$d1="(1) Past returns do not guarantee future returns";
$d2="
(2) Best scenario: It is the difference between the target value and the aggregate market price of the portfolio. To calculate the target value, we apply a multiple to the normalized cash flow based on our estimate of each company.
(3) Worst scenario: Calculated with the VALUE AT RISK Methodology (VaR) 2.32 sigmas, 99% confidence level of the normal distribution at 1 month.
(4) It is calculated by dividing the market capitalization of each company by its normalized cash flow based on our estimates.
(5) It is the result of dividing the normalized cash flow based on our estimates, by the Enterprise Value.
(6) We calculate it by dividing the normalized operating result based on our own estimates, after taxes, by the capital employed (ex – goodwill) in order to get the business profitability.";
$d3="(2) Due to the lack of historic data, class C statistics are used";
$notacomision='';
if($fondo==21 || $fondo==23) {$notacomision='Management fee is partially waived to 1.25% (effective December 2018 until further notice)';}
$comisionresultadotitulo='Comission on results';
$comisionreembolsotitulo='Reimbursement comission';
$highwatermarktitulo='High Water Mark';
$ratiostitulo="Ratios";
$distribucionactivos="Asset Distribution";
$principalessectores="Main Sectors.";
$textopatrimonio=" millions of euros";
$and='&';
$otrostexto='Others';
$valorliquidativo='NAV';
$enelmes='MTD';
$enelano='YTD';
$desdeelinicio='Since inception';
$historicorentabilidad='Fund Performance (1)';
$nombrefondo='Fund';
$diferencia='Difference';
$rentabilidadacumulada='Returns (1)';
$vartexto='Max. monthly loss expected(3)';
$titulografica1='Fund Performance vs benchmark';
$contribucionrentabilidad='Performance Contribution';
$incrementa='INCREASES';
$disminuye='DECREASES';
$distribucionhistorica='Return Distribution';
$subtitulodistribucion='Percentage of months in which returns have been within the range';
$subtitulografica1='Growth of EUR 100';
if ($fondo==15 || $fondo==17 || $fondo==19) {$subtitulografica1='Growth of USD 100';}
$estadisticas='Statistics'.$d3code.'
';
$rentabilidadanualizada='Annualised Return';
$volatilidad='Standard Dev';
$potencial='Upside Potential'.$sup2.'';
$ano1='1 year';
$ano3='3 years';
$ano5='5 years';
$ano10='10 years';
$indicadorriesgo='Risk Indicator';
$top5='Top 5 positions';
$menor='Below';
$entre='Between';
$mayor='Over';
//$datos='Data as of 1Q 2019';
$fechadatos=$mesencurso;
$distribuciongeografica='Geographical Distribution';
$usa='USA';
$zonaeuro='Eurozone';
$restoeuropa='Other Europe';
$asia='Asia';
$otros='Other';
$liquidez='Cash';
$espana='Spain';
$portugal='Portugal';
$distribucionsectorial='Sectorial Distribution';
$objetivoinversion='Investment objective';
$equipogestor='Investment manager';
$estrategiainversion='Investment Strategy';
$datosdelfondo='General Information';
$gestora='Fund Manager';
$depositario='Custodian Bank';
$estructuralegal='Legal Status';
$paisregistro='Country of registration';
$fechacreacion='Inception date';
$cierreanofilcal='Close of fiscal year';
$horacorte='Cut-off time';
$valoraciontitulo='NAV valuation';
$comisiongestion='Management Fees';
$otrosgastos='Other Ongoing Charges';
$isin='ISIN';
$codigobloomberg='Bloomberg:';
$activosbajogestion='AUM:';
$numeroposiciones='Number of holdings';
$contactoinversor='INVESTOR CONTACT';
$informacionrelevante='Disclaimer';
$contenidodisclaimer='This document is of a commercial nature and is supplied solely for informative purposes and may not at any time be considered a contractual element. recommendation. personalised advice or offer. Nor may it be considered as a replacement of the Fundamental Investor Data (FID) or any other mandatory legal information which must be consulted prior to taking an investment decision. In the case of any discrepancy. the legal information shall prevail. All legal information will be available at the head office of the Management Company and through the website: www.cobasam.com. All performance data are in EUR currency. and net of expenses and fees. Investing in equities can lead to losses of invested capital and is inadvisable for time horizons of less than 5 years.';
}
//cambio literales fondos de pensiones
if($fondo==8 || $fondo==10) {
$gestora='Gestora del fondo';
$depositario='Depositario';
$estructuralegal='Código PP DGS';
$paisregistro='Fondo de Pensiones';
$fechacreacion='Código FP DGS';
$cierreanofilcal='Fecha de registro';
$horacorte='Comercializador';
$valoraciontitulo='Valoración';
$comisiongestion='Comisión gestión';
$otrosgastos='Otros Gastos Corrientes';
$isin='Aportación mínima extraordinaria';
$codigobloomberg='Código Bloomberg';
$activosbajogestion='Activos bajo gestión';
$numeroposiciones='Número de posiciones';
}
//Quito la divisa para fondos de España
if ($Divisa=="EUR") {
$Divisa='€';
}
if ($Divisa=="USD") {
$Divisa='$';
}
if ($fondo<13 || $fondo>100) {
$Divisa='';
}
//Oculto la gráfica top5 para el fondo 6
if ($fondo==6 || $fondo==21 || $fondo==23 || $fondo==2676 || $fondo==2677) {
?>
format("Y-m-d");
}
$gmes="";
$gcotizacion="";
$cotizacionanteriorbenchmark=100;
$bbase100="";
$sql10="select c.Fecha, c.Cotizacion, b.Base100 from Cotizaciones c left join Benchmark b on b.Fondo=c.Cod_Entidad and b.Fecha=c.Fecha WHERE c.Cod_Entidad='$fondo' and c.Fecha<='$fechamaxima' order by c.Fecha ASC";
$stmt10 = sqlsrv_query( $conn, $sql10);
while( $row = sqlsrv_fetch_array( $stmt10, SQLSRV_FETCH_ASSOC))
{
$fechafondo=$row['Fecha']->format("Y-m-d");
$gmes=$gmes."'".$row['Fecha']->format("Y-m-d")."',";
$gcotizacion=$gcotizacion.$row['Cotizacion'].',';
$cotizb=$row['Base100'];
if(!$cotizb) {
$bbase100=$bbase100.$cotizacionanteriorbenchmark.',';
} else {
$bbase100=$bbase100.$row['Base100'].',';
$cotizacionanteriorbenchmark=$cotizb;
}
}
$gmes= substr($gmes,0,-1);
$gcotizacion= substr($gcotizacion,0,-1);
$bbase100= substr($bbase100,0,-1);
//ajustee literales
$sup5='(5)';
$sup6='(6)';
$sup7='(7)';
if ($idioma=='es') {
$vartexto='Pérdida máx. esperada mensual(4)';
$d2="
(3) Mejor escenario: Es la diferencia entre el valor objetivo y el precio de mercado agregado de la cartera. Para calcular el valor objetivo, aplicamos un múltiplo al flujo de caja normalizado en base a estimaciones propias de cada compañía.
(4) Peor escenario: Calculado con Metodología VALUE AT RISK (VaR) 2,32 sigmas, nivel de confianza del 99% de la distribución normal a 1 mes.
(5) Se calcula dividiendo la capitalización bursátil de cada compañía entre su flujo de caja normalizado en base a estimaciones propias.
(6) Es el resultado de dividir el flujo de caja normalizado en base a estimaciones propias, entre el Enterprise Value.
(7) Lo calculamos dividiendo el resultado operativo normalizado en base a estimaciones propias, después de impuestos entre el capital empleado (ex - fondo de comercio) para ver la rentabilidad intrínseca del negocio.";
} else {
$vartexto='Max. monthly loss expected(4)';
$d2="
(3) Best scenario: It is the difference between the target value and the aggregate market price of the portfolio. To calculate the target value, we apply a multiple to the normalized cash flow based on our estimate of each company.
(4) Worst scenario: Calculated with the VALUE AT RISK Methodology (VaR) 2.32 sigmas, 99% confidence level of the normal distribution at 1 month.
(5) It is calculated by dividing the market capitalization of each company by its normalized cash flow based on our estimates.
(6) It is the result of dividing the normalized cash flow based on our estimates, by the Enterprise Value.
(7) We calculate it by dividing the normalized operating result based on our own estimates, after taxes, by the capital employed (ex – goodwill) in order to get the business profitability.";
}
}
if ($fondo == 2676){
if ($idioma=='es') {
$vartexto='Pérdida máx. esperada mensual(2)';
$sup5='(3)';
$sup6='(4)';
$sup7='(5)';
$d2="
(3) Se calcula dividiendo la capitalización bursátil de cada compañía entre su flujo de caja normalizado en base a estimaciones propias.
(4) Es el resultado de dividir el flujo de caja normalizado en base a estimaciones propias, entre el Enterprise Value.
(5) Lo calculamos dividiendo el resultado operativo normalizado en base a estimaciones propias, después de impuestos entre el capital empleado (ex - fondo de comercio) para ver la rentabilidad intrínseca del negocio.";
} else {
$vartexto='Max. monthly loss expected(2)';
$d2="
(3) It is calculated by dividing the market capitalization of each company by its normalized cash flow based on our estimates.
(4) It is the result of dividing the normalized cash flow based on our estimates, by the Enterprise Value.
(5) We calculate it by dividing the normalized operating result based on our own estimates, after taxes, by the capital employed (ex – goodwill) in order to get the business profitability.";
}
}
if ($fondo == 2677){
if ($idioma=='es') {
$vartexto='Pérdida máx. esperada mensual(3)';
$sup5='(4)';
$sup6='(5)';
$sup7='(6)';
$d2="
(4) Se calcula dividiendo la capitalización bursátil de cada compañía entre su flujo de caja normalizado en base a estimaciones propias.
(5) Es el resultado de dividir el flujo de caja normalizado en base a estimaciones propias, entre el Enterprise Value.
(6) Lo calculamos dividiendo el resultado operativo normalizado en base a estimaciones propias, después de impuestos entre el capital empleado (ex - fondo de comercio) para ver la rentabilidad intrínseca del negocio.";
} else {
$vartexto='Max. monthly loss expected(3)';
$d2="
(4) It is calculated by dividing the market capitalization of each company by its normalized cash flow based on our estimates.
(5) It is the result of dividing the normalized cash flow based on our estimates, by the Enterprise Value.
(6) We calculate it by dividing the normalized operating result based on our own estimates, after taxes, by the capital employed (ex – goodwill) in order to get the business profitability.";
}
}
//Ajuste estadísticas
?>
|
|
|
|
|
|
Benchmark |
|
|
|
|
|
|
| Sharpe |
|
|
| Alpha |
|
|
| Beta |
|
|
| Tracking error |
|
|
|
|
|
|
|
|
| PER |
|
| Unleveraged FCF Yield |
|
| ROCE |
|
|
|
|
Dpto. de Relación con Inversores
Calle José Abascal 45,
3ª planta
28003 Madrid
900 15 15 30 (España)
+34 91 755 68 00
Madrid
+34 91 755 68 00
institutional@cobasam.com
|
|
|
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
| : |
Madrid
Madrid
+34 91 755 68 00
institutional@cobasam.com
|
Dpto. de Relación con Inversores
Calle José Abascal 45,
3ª planta
28003 Madrid
900 15 15 30 (España)
+34 91 755 68 00
|