예제 #1
0
def writeCsvCanje(file, data, columnnames, operacion):

    data = [list(elem) for elem in data]

    #creacion de precios, porcentajes y link
    for i, prop in enumerate(data):

        #arreglar precio
        precio = prop[0]
        if operacion == "venta":
            unf = uf.getUf()
            precio = precio / unf
            precio = int(precio)
            precioStr = str(precio)
        else:

            precioStr = str(precio)

        prop[0] = precioStr
        ufn = uf.getUf()
        #quitar decimales a valores
        prop[1] = int(prop[1])
        prop[2] = int(prop[2])
        prop[3] = int(prop[3])
        prop[4] = int(prop[4])
        prop[5] = int(prop[5])

    with open(file, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile,
                            delimiter=';',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow(columnnames)
        for row in data:
            writer.writerow(row)
예제 #2
0
def calcularDistancia(i,data,fail):

    distancia=[]
    for j in data:
        if i[7]=="Departamento":
            tipo="departamento"
        elif i[7]=="Casa":
            tipo="casa"
        elif i[7]=="Oficina":
            tipo="oficina"
        try:
            if (j[1]>past) and (tipo==j[4]) and ("arriendo"==j[3]) and (float(i[2])==j[6]) and (float(i[3])==j[7]) and (float(i[10])==j[12]):
                lat1=i[8]
                long1=i[9]
                lat2=j[10]
                long2=j[11]
                r=6371000
                c=pi/180
                distance= 2*r*asin(sqrt(sin(c*(lat2-lat1)/2)**2 + cos(c*lat1)*cos(c*lat2)*sin(c*(long2-long1)/2)**2))

                if (distance < 1500) and (abs(i[4]/j[8]-1)<0.2) and (abs(i[5]/j[9]-1)<0.4):
                    d=sqrt(distance*distance+(100*abs(i[4]-j[8])*(100*abs(i[4]-j[8])))+(100*abs(i[5]-j[9])*(100*abs(i[5]-j[9]))))
                    subdistancia=[]
                    subdistancia.append(j[0])
                    subdistancia.append(d)
                    distancia.append(subdistancia)
        except:
            continue

    distancias=sorted(distancia,key=lambda x:x[1])
    try:
        distancias=distancias[:40]
    except:
        distancias=distancia

    prices=[]
    count=0
    for d in distancias:
        p=precio_from_portalinmobiliario(d[0])
        if (count==1) and (q==p):
            continue
        else:
            prices.append(p)
            count=1
            q=p
    try:
        cosa=mean(prices)
        precio=cosa[0]
        unf=uf.getUf()
        precio2=precio/unf

        rentabilidad=(precio2*12)/i[1]

        insertarRentabilidada(precio,rentabilidad,i[0])
    except:
        fail=fail+1
예제 #3
0
def crearFicha(sitio,id,mail,tipoficha):
    links=[]
    text2=''
    auxPhone=0
    #Determinar tipo de informe
    pro=False
    interna=False
    full=False

    if tipoficha==2:
        pro=True
    elif tipoficha==3:
        interna=True
    elif tipoficha==4:
        interna=True
        pro=True


    #Chequear que sitio este bien
    sitio=sitio.lower()

    if('portal' in sitio):
        sitio='portal'
    elif('yapo' in sitio):
        sitio='yapo'
    else:
        text='Sitio ingresado es incorrecto. Favor ingresar portalinmobiliario o yapo.'
        return(text)
    #Chequear que mail este bien
    if ('@' not in mail):
        text='Email incorrecto. Favor ingresar correo válido.'
        return(text)
    if ('.' not in mail):
        text='Email incorrecto. Favor ingresar correo válido.'
        return(text)

    #sacar informacion de bbdd, y chequear que propiedad existe:
    propiedad=obtenerProp(id,sitio)

    if len(propiedad)<1:
        text='¨Propiedad no se encuentra en la base de datos.'
        return(text)

    else:
        propiedad=list(propiedad)

        nombre=str(propiedad[0])
        region=str(propiedad[1])
        regionP=region
        regionY=region
        if region=='15':
            regionP='metropolitana'
        if region=='metropolitana':
            regionY='15'
        operacion=str(propiedad[2])
        tipo=str(propiedad[3])
        precio=float(propiedad[4])
        dormitorios=str(propiedad[5])
        banos=str(propiedad[6])
        metrosmin=str(propiedad[7])
        metrosmax=str(propiedad[8])
        estacionamientos=str(propiedad[9])
        bodegas=str(propiedad[10])
        lat=str(propiedad[11])
        lon=str(propiedad[12])
        link=str(propiedad[13])
        if sitio=='portal':
            if operacion=='venta':
                comuna=str(link.split('/')[5])
                comuna=comuna.replace('-'+str(regionP),'')
                comuna=comuna.replace('-',' ')
                comuna=comuna.capitalize()
                propiedad.append(comuna)

            else:
                comuna=str(link.split('/')[6])
                comuna=comuna.replace('-metropolitana','')
                comuna=comuna.replace('-',' ')
                comuna=comuna.capitalize()
                propiedad.append(comuna)
        else:
            comuna=str(propiedad[14])
    #Revisar si existe aun la publicacion
    if not pubPortalExiste.publicacionExiste(link):
        text='Propiedad ya no se encuentra disponible en el sitio.'
        return(text)
    #sacar informacion de la publicacion
    #sacar urls fotos portal
    matrixdescripcion=[]
    matrixcounter=0
    matrixdescripcion.append('')

    if sitio=='portal':
        first=True
        url=[]
        page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()})
        metatext=page.text
        metatext=metatext.split(' ')
        descripcion=[]
        savedescripcion=False
        for texto in metatext:

            if 'propiedad-descr' in texto:
                savedescripcion=True
            if '/div' in texto:
                savedescripcion = False
            if savedescripcion:
                descripcion.append(str(texto))

        descripcion=descripcion[2:]
        print(descripcion)

        if not interna:
            for desc in descripcion:
                desc=desc.replace('   ','')
                desc=desc.replace('<br />',' ')
                desc=desc.replace('<br/>',' ')
                desc=desc.replace('<br>',' ')
                desc=desc.replace('<b/>','')
                desc=desc.replace('<b>','')
                desc=desc.replace('</b>','')
                desc=desc.replace('<br','')
                desc=desc.replace('/>','')
                desc=desc.replace('&#237;','í')
                desc=desc.replace('&#233;','é')
                desc=desc.replace('&#243;','ó')
                desc=desc.replace('&#225;','á')
                desc=desc.replace('&#250;','ú')
                desc=desc.replace('&#241;','ñ')
                desc=desc.replace('&#209;','Ñ')

                if "+56" in desc:
                    desc="**"
                if len(desc)>=6:
                    try:
                        desc.replace('\n',"")
                        int(desc)
                        desc="**"
                    except:
                        pass

                if "@" in desc:
                    desc="***"

                if ((len(matrixdescripcion[matrixcounter])+len(desc))>=78):

                    matrixcounter+=1
                    matrixdescripcion.append('')
                    if desc!= '':
                        matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)
                else:
                    if first:
                        if desc!= '':
                            matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)
                        first=False
                    else:
                        if desc!= '':
                            matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc)
            print(matrixdescripcion)
            for x,matrix in enumerate(matrixdescripcion):
                matrix=matrix.replace('<br />','\n')
                matrix=matrix.replace('<br/>','\n')
                matrix=matrix.replace('<br>','\n')
                matrix=matrix.replace('<b/>','')
                matrix=matrix.replace('<b>','')
                matrix=matrix.replace('</b>','')
                matrixdescripcion[x]=matrix
            descripcion='\n'.join(matrixdescripcion)
            propiedad.append(descripcion)

        else:
            descripcion=' '.join(descripcion)
            descripcion=descripcion.replace('   ','')
            descripcion=descripcion.replace('<br />','\n')
            descripcion=descripcion.replace('<br/>','\n')
            descripcion=descripcion.replace('<br>','\n')
            descripcion=descripcion.replace('<b/>','')
            descripcion=descripcion.replace('<b>','')
            descripcion=descripcion.replace('</b>','')
            descripcion=descripcion.replace('<br','')
            descripcion=descripcion.replace('/>','')
            descripcion=descripcion.replace('&#237;','í')
            descripcion=descripcion.replace('&#233;','é')
            descripcion=descripcion.replace('&#243;','ó')
            descripcion=descripcion.replace('&#225;','á')
            descripcion=descripcion.replace('&#250;','ú')
            descripcion=descripcion.replace('&#241;','ñ')
            descripcion=descripcion.replace('&#209;','Ñ')



            propiedad.append(descripcion)

        for meta in metatext:

            if 'https://image.portalinmobiliario.cl/Portal/Propiedades' in meta and '1200' in meta:
                meta=meta.split('"')

                url.append(str(meta[1]))




    #Sacar urls fotos yapo
    else:

        url=[]
        page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()})
        metatext=page.text
        metatext=metatext.split(' ')
        descripcion=[]
        savedescripcion=False
        saveimg=False
        og=True

        for texto in metatext:

            if '<h4>Descripción</h4>' in texto:
                savedescripcion=True

            if og and 'og:image' in texto:
                saveimg=True
                og=False
            if 'img/yapo' in texto:
                saveimg=False
            if savedescripcion:
                descripcion.append(str(texto))
            if '</div>' in texto:
                savedescripcion = False
            if saveimg and 'img.yapo.cl/images' in texto:
                texto=texto.replace('content="','')
                texto.replace('"','')
                url.append(texto)
            if 'phone-url' in texto:
                texto=texto.split('"')
                texto=texto[1]
                auxPhone=texto
                auxPhone='https://www.yapo.cl'+auxPhone
        descripcion=descripcion[1:]
        first=True
        print(descripcion)
        for desc in descripcion:
            desc=desc.replace('\n',' ')
            desc=desc.replace('<br />','\n')
            desc=desc.replace('</div>','\n')
            desc=desc.replace('<br>','\n')
            desc=desc.replace('<br','')
            desc=desc.replace('/>','')
            desc=desc.replace('itemprop="description">',"")
            desc=desc.replace('</p>','\n')
            desc=desc.replace("\t","")
            desc=desc.replace('<!','')
            desc=desc.replace('--','')
            desc=desc.replace('  ','')
            desc=desc.replace('\n',' ')


            if ((len(matrixdescripcion[matrixcounter])+len(desc))>=78):

                matrixcounter+=1
                matrixdescripcion.append('')
                matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)
            else:
                if first:
                    matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)
                    first=False
                else:
                    matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc)

        print(matrixdescripcion)
        descripcion='\n'.join(matrixdescripcion)

        propiedad.append(descripcion)





        try:
            print(auxPhone)
            response = requests.get(auxPhone, headers={'User-Agent': agentCreator.generateAgent()})
            auxphone2=auxPhone
            img = Image.open(BytesIO(response.content))
            img=img.convert('L')
            img=img.convert('1')
            img.save("auxphone.gif")
            auxPhone=1
        except:
            pass
    lenfotos=len(url)

    if len(url)==0:
        print("la propiedad no cuenta con fotografias")
    else:
        print('total fotos: '+str(len(url)))
        for x,u in enumerate (url):
            u=u.replace('"','')
            response = requests.get(u)
            img = Image.open(BytesIO(response.content))
            img.save(str(x)+" foto.jpg")

    if not interna:
        imagenDescripcion = Image.new('RGB', (456, 345), color = (255, 255, 255))

        d = ImageDraw.Draw(imagenDescripcion)
        f= ImageFont.truetype('arial.ttf',12)
        d.text((0,0), descripcion,font=f, fill=(0,0,0))

        imagenDescripcion.save('imagenDescripcion.png')

    datospro = []
    if pro:
        comunaP = (comuna.replace(' ', '-') + '-'+str(region)).lower()
        listacomunas=[]
        listacomunas.append(comuna)
        propsP = reportes.from_portalinmobiliario(tipo, regionP,listacomunas, True)
        propsY = reportes.from_yapo(tipo, regionY,listacomunas, True, True)
        props = propsP + propsY

        if operacion=='venta':

            print("la comuna para calcular la rentabilidad promedio es:")
            print(comunaP)
            rentaPromedio = reportes.rentaPProm(tipo, float(dormitorios), float(banos), float(estacionamientos), comunaP)

            print("input tasacion ficha")
            print(tipo)
            print(float(lat))
            print(float(lon))
            print(float(metrosmin))
            print(float(metrosmax))
            print(float(dormitorios))
            print(float(banos))
            print(float(estacionamientos))



            tasacionVenta = tb2.calcularTasacionData("venta", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios),
                                                     float(banos), float(estacionamientos), props)
            tasacionArriendo = tb2.calcularTasacionData("arriendo", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios),
                                                     float(banos), float(estacionamientos), props)


            precioV = tasacionVenta[0] * uf.getUf()
            precioA = tasacionArriendo[0]
            print("el precio tasado de venta inicial es: "+str(precioV))
            print("el precio tasado de arriendo inicial es: "+str(precioA))
            links=tasacionVenta[3]



            if precioV is None or precioV < 0.1:
                pro=False


            try:
                precioA = tasacionArriendo[0]
                rentaV = ((precioV - precio) / precio)
            except:
                pro=False
                text2='No se ha podido realizar tasación'
                print('fail 1')

            if precioA is None or precioA < 0.01:
                pro=False


            try:
                rentaA = (precioA * 12 / precio)
                print('succes 2.1')
                print(precioA)
                print(precioV)
                rentaPP = (precioA * 12 / precioV)
                print('succes 2.2')
            except:
                pro=False
                text2='No se ha podido realizar tasación'
                print('fail 2')


            if pro:
                if rentaA > 0.2:
                    pro=False
                    print('fail 3')


                if rentaPP < 1.2*rentaPromedio:

                    try:
                        print("[GeneradorReportes] renta pp muy baja, recalculando precio")
                        print("precio anterior:"+str(precioV))
                        precioV = precioA * 12 / rentaPromedio
                        rentaV = ((precioV - precio) / precio)
                        rentaPP = (precioA * 12 / precioV)
                        print("precio nuevo:"+str(precioV))


                    except:
                        pro=False
                        text2='No se ha podido realizar tasación'
                        print('fail 4')

                if rentaPP > 0.15:
                    try:
                        precioV = precioA * 12 / 0.15
                        rentaV = ((precioV - precio) / precio)
                    except:
                        pro=False
                        text2='No se ha podido realizar tasación'
                        print('fail 52')

                if rentaA < 0:
                    pro=False


            if pro:
                # precio venta tasado
                datospro.append(precioV)
                # rentabilidad de venta
                datospro.append(float(rentaV))

                # precio arriendo tasado
                datospro.append(precioA)
                # rentabilidad de arriendo
                datospro.append(float(rentaA))



        else:
            try:
                tasacionArriendo = tb2.calcularTasacionData("arriendo", tipo, float(lat), float(lon), float(metrosmin),float(metrosmax),float(dormitorios),
                                                     float(banos), float(estacionamientos), props)
            except:
                pro=False
                text2='No se ha podido realizar tasación'
                print('fail 6')


            try:
                precioA = tasacionArriendo[0]
                links=tasacionArriendo[3]

            except:
                pro=False
                text2='No se ha podido realizar tasación'
                print('fail 72')

            if pro:
                if precioA is None or precioA < 0.01:
                    pro = False
                    text2='No se ha podido realizar tasación'
                    print('fail 8')


            if pro:
                # precio arriendo tasado
                datospro.append(precioA)
                # rentabilidad de arriendo

    datoscontacto = []
    if interna:

        if sitio=='portal':
            try:
                email, telefono, dueno = reportes.getDatosDueno(str(id))
            except:
                email = "NN"
                telefono = "NN"
                dueno = "NN"

        else:
            email = "NN"
            if auxPhone == 1:
                telefono=auxphone2
            else:
                telefono = "NN"
            dueno = 'NN'
        datoscontacto.append(email)
        datoscontacto.append(telefono)
        datoscontacto.append(dueno)


    #Crear PDF
    if interna:
        nombrearchivo="Ficha Propiedad Sitio:"+str(sitio)+" Id:"+str(id)+".pdf"
    else:
        nombrearchivo="Ficha Propiedad Sitio:"+str(sitio)+", "+str(operacion)+", "+str(tipo)+", "+str(region)+", "+str(comuna)+".pdf"

    print(nombrearchivo)

    pdfCreatorFichas.crearPdfFicha(nombrearchivo,id,propiedad,lenfotos,pro,datospro,interna,datoscontacto,regionP,links)
    print("pdf generado con exito")
    #Enviar PDF
    sendmail.sendMail(mail,"",nombrearchivo)

    #Eliminar del servidor

    if len(url)==0:
        pass
    else:
        for x,u in enumerate (url):
            os.remove(str(x)+" foto.jpg")
    try:
        os.remove("auxphone.gif")
    except:
        pass

    if not interna:
        try:
            os.remove("imagenDescripcion.png")
        except:
            pass
    os.remove(nombrearchivo)

    #Retornar exito
    text = "Ficha creada para la propiedad: "+str(id)+" obtenida del sitio: "+str(sitio)+", enviada con éxito al correo: "+str(mail)+"."
    if text2!='':
        text=text2+'. '+text
    return(text)
def createPdfReport(cliente, fileName, data, headers, operacion):

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    image = Image('bull_logo2.png', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)

    Story.append(Spacer(1, 12))

    fecha_hoy = datetime.today().strftime('%d-%m-%Y')

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))

    ptext = '<font size=12>%s</font>' % fecha_hoy

    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    # Create return address
    full_name = "BullEstate"
    ptext = '<font size=12>%s</font>' % full_name
    Story.append(Paragraph(ptext, styles["Normal"]))

    web = '<link href="' + 'http://www.bullestate.cl' + '" color="blue">' + 'www.bullestate.cl' + '</link>'
    Story.append(platypus.Paragraph(web, PS('body')))

    mail = '<a href="mailto:[email protected]" color="blue">[email protected]</a>'
    Story.append(platypus.Paragraph(mail, PS('body')))

    Story.append(Spacer(1, 12))
    ptext = '<font size=12>Estimada/o %s:</font>' % cliente.split()[0].strip()
    Story.append(Paragraph(ptext, styles["Normal"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Según los requerimientos presentados por Ud, las oportunidades inmobiliarias encontradas con ' \
            'fecha %s, son las siguientes:</font>' % fecha_hoy
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    nrCols = 11
    nrRows = len(data) + 1

    data = [list(elem) for elem in data]

    #creacion de precios, porcentajes y link
    for i, prop in enumerate(data):
        #porcentaje
        rent = float(prop[9])
        rent = int(rent * 1000)
        rent = float(rent / 10)
        rent = str(rent) + "%"
        prop[9] = rent
        if (operacion == "venta"):
            rent = float(prop[11])
            rent = int(rent * 1000)
            rent = float(rent / 10)
            rent = str(rent) + "%"
            prop[11] = rent

        #arreglar precio
        precio = prop[0]
        if operacion == "venta":
            unf = uf.getUf()
            precio = precio / unf
            precio = int(precio)
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = "UF " + precioStr.replace(",", ".")
        else:
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = "$ " + str(precioStr)

        prop[0] = precioStr
        ufn = uf.getUf()
        #quitar decimales a valores
        prop[1] = int(prop[1])
        prop[2] = int(prop[2])
        prop[3] = int(prop[3])
        prop[4] = int(prop[4])
        prop[5] = int(prop[5])
        prop[7] = int(prop[7])

        if (operacion == "venta"):
            prop[8] = int(prop[8] / ufn)
            prop[8] = format(prop[8], ',.2f')
            prop[8] = prop[8][:-3]
            prop[8] = "UF " + str(prop[8])
            prop[10] = int(prop[10])
            prop[10] = format(prop[10], ',.2f')
            prop[10] = prop[10][:-3]
            prop[10] = "$ " + str(prop[10])
            #link
            link = str(prop[12])
            linkHtml = '<link href="' + link + '" color="blue">' + "Link" + '</link>'
            prop[12] = platypus.Paragraph(linkHtml, PS('body'))

        else:

            prop[8] = int(prop[8])
            prop[8] = format(prop[8], ',.2f')
            prop[8] = prop[8][:-3]
            prop[8] = "$ " + str(prop[8])
            #link
            link = str(prop[10])
            linkHtml = '<link href="' + link + '" color="blue">' + "Link" + '</link>'
            prop[10] = platypus.Paragraph(linkHtml, PS('body'))

        #agregar numerador
        data[i] = [i + 1] + prop

    headers = ["Nº"] + headers
    data = [headers] + data
    #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
    t = Table(data)
    t.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
        ]))

    Story.append(t)
    Story.append(Spacer(2, 24))

    ptext = '<font size=12>*D=Dormitorios  B=Baños  E=Estacionamientos  P.P=Precio venta predicho  Rent.P=Rentabilidad Venta  Rent.A=Rentabilidad Arriendo </font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Si ud. esta interesada/o en visitar algunas de las propiedades señaladas, le solicitamos escribirnos a la brevedad ' \
            'para agendar una visita.</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    ptext = '<font size=12>Sin otro particular, se despide atentamente:</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    image = Image('firmaSergei.jpg', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)

    ptext = '<font size=12>Sergei Schkolnik</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))

    doc.build(Story)
예제 #5
0
def writeCsv(file, data, columnnames, operacion):

    data = [list(elem) for elem in data]

    #creacion de precios, porcentajes y link
    for i, prop in enumerate(data):
        #porcentaje
        if "Rentabilidad Venta" in columnnames:
            index = columnnames.index("Rentabilidad Venta")
            rent = float(prop[index])
            rent = int(rent * 1000)
            rent = float(rent / 1000)
            rentS = str(rent).replace('.', ',')
            prop[index] = rentS
        if "Rentabilidad Arriendo" in columnnames:
            index = columnnames.index("Rentabilidad Arriendo")
            rent = float(prop[index])
            rent = int(rent * 1000)
            rent = float(rent / 1000)
            rentS = str(rent).replace('.', ',')
            prop[index] = rentS
        unf = uf.getUf()

        #arreglar precio
        precio = prop[0]

        #venta
        if operacion == "venta":
            precio = precio / unf
            precio = int(precio)
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = precioStr.replace(",", ".")

            if "Precio Venta Tasado" in columnnames:
                index = columnnames.index("Precio Venta Tasado")
                precio2 = prop[index] / unf
                precio2 = int(precio2)
                precioStr2 = format(precio2, ',.2f')
                precioStr2 = precioStr2[:-3]
                precioStr2 = precioStr2.replace(",", ".")
                prop[index] = precioStr2

        #arriendo
        else:
            precioStr = format(precio, ',.2f')
            precioStr = precioStr[:-3]
            precioStr = str(precioStr)
            if "Precio Arriendo Tasado" in columnnames:
                index = columnnames.index("Precio Arriendo Tasado")
                precio2 = int(prop[index])
                precioStr2 = format(precio2, ',.2f')
                precioStr2 = precioStr2[:-3]
                prop[index] = precioStr2

        prop[0] = precioStr

        #quitar decimales a valores
        if "Utiles" in columnnames:
            index = columnnames.index("Utiles")
            prop[index] = int(prop[index])

        if "Total" in columnnames:
            index = columnnames.index("Total")
            prop[index] = int(prop[index])

        if "Estacionamientos" in columnnames:
            index = columnnames.index("Estacionamientos")
            prop[index] = int(prop[index])

        if "Bodegas" in columnnames:
            index = columnnames.index("Bodegas")
            prop[index] = int(prop[index])

        if "Distancia metro" in columnnames:
            index = columnnames.index("Distancia metro")
            prop[index] = int(prop[index])

    with open(file, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile,
                            delimiter=';',
                            quotechar='|',
                            quoting=csv.QUOTE_MINIMAL)
        writer.writerow(columnnames)
        for row in data:
            writer.writerow(row)
예제 #6
0
import math
import pymysql as mysql
import math
from math import radians, sin, cos, acos, asin,pi,sqrt
from datetime import datetime, timedelta, date
past = datetime.now() - timedelta(days=90)
past=datetime.date(past)
yesterday = datetime.now() - timedelta(days=3)
yesterday=datetime.date(yesterday)
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import uf

uf1=uf.getUf()



def insertarTasacion(precio,preciomin,preciomax,id):
    sql = "UPDATE tasaciones SET precio='"+str(precio)+"',preciomin='"+str(preciomin)+"',preciomax='"+str(preciomax)+"' WHERE id='"+str(id)+"'"


    mariadb_connection = mysql.connect(user='******', password='******', host='127.0.0.1', database='bullestate')

    cur = mariadb_connection.cursor()
    cur.execute(sql)
    mariadb_connection.commit()
    mariadb_connection.close()

def from_tasaciones():
    mariadb_connection = mysql.connect(user='******', password='******', host='127.0.0.1', database='bullestate')
예제 #7
0
def calcularTasacion(operacion,tipo,lat,lon,util,total,dormitorios,banos,estacionamientos):


    data = from_portalinmobiliario()
    distanciat0=[]
    distanciat1=[]
    distanciat2_1=[]
    distanciat2_2=[]
    distanciat3_1=[]
    distanciat3_2=[]
    distanciat4_1=[]
    distanciat4_2=[]
    k0=[0]*14
    k1=[0]*14
    k21=[0]*14
    k22=[0]*14
    k31=[0]*14
    k32=[0]*14
    k41=[0]*14
    k42=[0]*14

    for j in data:
        # i3=op, i4=tipo, i5=precio, i6=dorms, i7=baños, i12= estacionamientos i8=util, i9=total
        if (j[1]>past) and (j[2]>yesterday) and (operacion==j[3]) and (tipo==j[4]):
            lat1=lat
            long1=lon
            lat2=j[10]
            long2=j[11]
            r=6371000
            c=pi/180
            distance= 2*r*asin(sqrt(sin(c*(lat2-lat1)/2)**2 + cos(c*lat1)*cos(c*lat2)*sin(c*(long2-long1)/2)**2))

            #T0
            if (distance < 1000) and (abs(util/j[8]-1)<0.1) and (abs(total/j[9]-1)<0.2) and (dormitorios==j[6]) and (banos==j[7]) and (estacionamientos==j[12]) and ((k0[5]!=j[5]) or (k0[8]!=j[8]) or (k0[9]!=j[9]) or (k0[6]!=j[6]) or (k0[7]!=j[7]) or (k0[12]!=j[12])):
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat0.append(j)
                k0=j
                j=j[:-1]


            #T1 REVISAR
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (dormitorios==j[6]) and (banos==j[7]) and (estacionamientos==j[12]) and ((k1[5]!=j[5]) or (k1[8]!=j[8]) or (k1[9]!=j[9]) or (k1[6]!=j[6]) or (k1[7]!=j[7]) or (k1[12]!=j[12])) :
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat1.append(j)
                j=j[:-1]
                k1=j

            #T2.1
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (dormitorios==j[6]) and (banos==j[7]) and (int(estacionamientos)>=(int(j[12])-1) and (int(estacionamientos)<=(int(j[12])+1))) and ((k21[5]!=j[5]) or (k21[8]!=j[8]) or (k21[9]!=j[9]) or (k21[6]!=j[6]) or (k21[7]!=j[7]) or (k21[12]!=j[12])) :
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat2_1.append(j)
                j=j[:-1]
                k21=j

            #T2.2
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (dormitorios==j[6]) and (banos==j[7]) and ((k22[5]!=j[5]) or (k22[8]!=j[8]) or (k22[9]!=j[9]) or (k22[6]!=j[6]) or (k22[7]!=j[7]) or (k22[12]!=j[12])) :
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat2_2.append(j)
                j=j[:-1]
                k22=j

            #T3.1
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (int(dormitorios)>=(int(j[6])-1) and (int(dormitorios)<=(int(j[6])+1))) and (banos==j[7]) and ((k31[5]!=j[5]) or (k31[8]!=j[8]) or (k31[9]!=j[9]) or (k31[6]!=j[6]) or (k31[7]!=j[7]) or (k31[12]!=j[12])) :
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat3_1.append(j)
                j=j[:-1]
                k31=j

            #T3.2
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (banos==j[7]) and ((k32[5]!=j[5]) or (k32[8]!=j[8]) or (k32[9]!=j[9]) or (k32[6]!=j[6]) or (k32[7]!=j[7]) or (k32[12]!=j[12])):
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat3_2.append(j)
                j=j[:-1]
                k32=j

            #T4.1
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (int(banos)>=(int(j[7])-1) and (int(banos)<=(int(j[7])+1))) and ((k41[5]!=j[5]) or (k41[8]!=j[8]) or (k41[9]!=j[9]) or (k41[6]!=j[6]) or (k41[7]!=j[7]) or (k41[12]!=j[12])):
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat4_1.append(j)
                j=j[:-1]
                k41=j

            #T4.2
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and ((k42[5]!=j[5]) or (k42[8]!=j[8]) or (k42[9]!=j[9]) or (k42[6]!=j[6]) or (k42[7]!=j[7]) or (k42[12]!=j[12])):
                d=sqrt(distance*distance+(100*abs(util-j[8])*(100*abs(util-j[8])))+(100*abs(total-j[9])*(100*abs(total-j[9]))))
                j.append(d)
                distanciat4_2.append(j)
                j=j[:-1]
                k42=j

    t_actual="A+"
    cota=10



    if len(distanciat0)>=cota:
        distancia=distanciat0

    elif len(distanciat1)>=cota:
        distancia=distanciat1
        t_actual="A-"
    elif len(distanciat2_1)>=cota:
        distancia=distanciat2_1
        t_actual="B+"
    elif len(distanciat2_2)>=cota:
        distancia=distanciat2_2
        t_actual="B-"
    elif len(distanciat3_1)>=cota:
        distancia=distanciat3_1
        t_actual="C+"
    elif len(distanciat3_2)>=cota:
        distancia=distanciat3_2
        t_actual="C-"
    elif len(distanciat4_1)>=cota:
        distancia=distanciat4_1
        t_actual="D+"
    elif len(distanciat4_2)>=5:
        distancia=distanciat4_2
        t_actual="D-"

    else:
        print("no se han encontrado propiedades para comparar")
        return 0,"E",len(distanciat4_2),[]

    distancias=sorted(distancia,key=lambda x:x[14])
    try:
        distancias=distancias[:40]
    except:
        distancias=distancia

    links = []
    for props in distancias:
            links.append(props[13])

    y_train = []
    x_train = []

    for e in distancias:
        x_train.append([e[8],e[9],e[6],e[7],e[12]])
        y_train.append(e[5])

    #y2_train=[]
    #y2_train.append(y_train)
    #y_train=y2_train
    x_train=np.array(x_train)
    y_train=np.array(y_train)
    #x_train=np.transpose(x_train)


    #print (x_train)
    #print(x_train.shape)
    #print (y_train)
    #print(y_train.shape)

    # Create linear regression object
    regr = linear_model.LinearRegression()

    # Train the model using the training sets
    regr.fit(x_train, y_train)
    #try:
     #   print("constante: "+str(regr.intercept_)+" coeficientes: " +str(regr.coef_))
    #except:
     #   print("unable to print coef")
    x_test = [util,total,dormitorios,banos,estacionamientos]
    x_test=np.array(x_test)
    x_test=np.transpose(x_test)
    # Make predictions using the testing set

    price=regr.intercept_
    c=0
    for coef in regr.coef_:
        price=price+coef*x_test[c]
        c=c+1

    #print(price)
    cota=len(distancias)+1
#print("y_pred = " + str(y_pred))
# The coefficients
#print('Coefficients: \n', regr.coef_)

    try:
        price = int(price/uf.getUf())
        return(price,t_actual,len(distancias),links)

    except:

        return -1,"ERROR",-1,[]
예제 #8
0
def calcularTasacionData(operacion, tipo, lat, lon, util, total, dormitorios,
                         banos, estacionamientos, data):

    ufn = uf.getUf()
    es_venta = operacion == "venta"
    distanciat000 = []
    distanciat00 = []
    distanciat0 = []
    distanciat1 = []
    distanciat2_1 = []
    distanciat2_2 = []
    distanciat3_1 = []
    distanciat3_2 = []
    distanciat4_1 = []
    distanciat4_2 = []
    distanciat5_1 = []
    distanciat5_2 = []
    distanciat5_3 = []
    distanciat6_0 = []

    tasacionsimple = False

    k000 = [0] * 14
    k00 = [0] * 14
    k0 = [0] * 14
    k1 = [0] * 14
    k21 = [0] * 14
    k22 = [0] * 14
    k31 = [0] * 14
    k32 = [0] * 14
    k41 = [0] * 14
    k42 = [0] * 14
    k51 = [0] * 14
    k52 = [0] * 14
    k53 = [0] * 14
    k60 = [0] * 14

    data = sorted(data, key=lambda x: x[5])

    for j in data:
        # i3=op, i4=tipo, i5=precio, i6=dorms, i7=baños, i12= estacionamientos i8=util, i9=total
        if (j[1] > past) and (j[2] > yesterday) and (operacion
                                                     == j[3]) and (tipo
                                                                   == j[4]):
            lat1 = lat
            long1 = lon
            lat2 = j[10]
            long2 = j[11]
            r = 6371000
            c = pi / 180
            distance = 2 * r * asin(
                sqrt(
                    sin(c * (lat2 - lat1) / 2)**2 + cos(c * lat1) *
                    cos(c * lat2) * sin(c * (long2 - long1) / 2)**2))

            #T000 (AA+)
            if (distance < 50) and (abs(util/j[8]-1)<0.1) and (abs(total/j[9]-1)<0.2) and \
                    ((dormitorios==j[6]) or tipo=="comercial") and (banos==j[7]) and ((estacionamientos==j[12]) or tipo=="casa" or tipo=="comercial") and \
                    ((k000[5]!=j[5]) or (k000[8]!=j[8]) or (k000[9]!=j[9]) or (k000[6]!=j[6]) or (k000[7]!=j[7]) or (k000[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat000.append(j)
                k000 = j
                j = j[:-1]

            #T00 (AA-)
            elif (distance < 500) and (abs(util/j[8]-1)<0.1) and (abs(total/j[9]-1)<0.2) and ((dormitorios==j[6]) or tipo=="comercial") and \
                    (banos==j[7]) and ((estacionamientos==j[12]) or tipo=="casa" or tipo=="comercial") and \
                    ((k00[5]!=j[5]) or (k00[8]!=j[8]) or (k00[9]!=j[9]) or (k00[6]!=j[6]) or (k00[7]!=j[7]) or (k00[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat00.append(j)
                k00 = j
                j = j[:-1]

            #T0
            elif (distance < 1000) and (abs(util/j[8]-1)<0.1) and (abs(total/j[9]-1)<0.2) and ((dormitorios==j[6]) or tipo=="comercial") \
                    and (banos==j[7]) and ((estacionamientos==j[12]) or tipo=="casa" or tipo=="comercial") \
                    and ((k0[5]!=j[5]) or (k0[8]!=j[8]) or (k0[9]!=j[9]) or (k0[6]!=j[6]) or (k0[7]!=j[7]) or (k0[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat0.append(j)
                k0 = j
                j = j[:-1]

            #T1 REVISAR
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and ((dormitorios==j[6]) or tipo=="comercial") \
                    and (banos==j[7]) and ((estacionamientos==j[12]) or tipo=="casa" or tipo=="comercial") and \
                    ((k1[5]!=j[5]) or (k1[8]!=j[8]) or (k1[9]!=j[9]) or (k1[6]!=j[6]) or (k1[7]!=j[7]) or (k1[12]!=j[12])) :

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat1.append(j)
                j = j[:-1]
                k1 = j

            #T2.1
            if (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and ((dormitorios==j[6]) or tipo=="comercial") \
                    and (banos==j[7]) and ((int(estacionamientos)>=(int(j[12])-1) or tipo=="casa" or tipo=="comercial") and (int(estacionamientos)<=(int(j[12])+1))) \
                    and ((k21[5]!=j[5]) or (k21[8]!=j[8]) or (k21[9]!=j[9]) or (k21[6]!=j[6]) or (k21[7]!=j[7]) or (k21[12]!=j[12])) :

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat2_1.append(j)
                j = j[:-1]
                k21 = j

            #T2.2
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and ((dormitorios==j[6]) or tipo=="comercial") \
                    and (banos==j[7]) and ((k22[5]!=j[5]) or (k22[8]!=j[8]) or (k22[9]!=j[9]) or (k22[6]!=j[6]) or (k22[7]!=j[7]) or (k22[12]!=j[12])) :

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat2_2.append(j)
                j = j[:-1]
                k22 = j

            #T3.1
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and \
                    ((int(dormitorios)>=(int(j[6])-1) or tipo=="comercial") and (int(dormitorios)<=(int(j[6])+1))) and (banos==j[7]) and \
                    ((k31[5]!=j[5]) or (k31[8]!=j[8]) or (k31[9]!=j[9]) or (k31[6]!=j[6]) or (k31[7]!=j[7]) or (k31[12]!=j[12])) :

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat3_1.append(j)
                j = j[:-1]
                k31 = j

            #T3.2
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (banos==j[7]) and \
                    ((k32[5]!=j[5]) or (k32[8]!=j[8]) or (k32[9]!=j[9]) or (k32[6]!=j[6]) or (k32[7]!=j[7]) or (k32[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat3_2.append(j)
                j = j[:-1]
                k32 = j

            #T4.1
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and (int(banos)>=(int(j[7])-1) and (int(banos)<=(int(j[7])+1))) and \
                    ((k41[5]!=j[5]) or (k41[8]!=j[8]) or (k41[9]!=j[9]) or (k41[6]!=j[6]) or (k41[7]!=j[7]) or (k41[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat4_1.append(j)
                j = j[:-1]
                k41 = j

            #T4.2
            elif (distance < 1000) and (abs(util/j[8]-1)<0.2) and (abs(total/j[9]-1)<0.4) and \
                    ((k42[5]!=j[5]) or (k42[8]!=j[8]) or (k42[9]!=j[9]) or (k42[6]!=j[6]) or (k42[7]!=j[7]) or (k42[12]!=j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat4_2.append(j)
                j = j[:-1]
                k42 = j
            #T5.1
            elif (distance < 1000) and ((k51[5] != j[5]) or (k51[8] != j[8]) or
                                        (k51[9] != j[9]) or (k51[6] != j[6]) or
                                        (k51[7] != j[7]) or
                                        (k51[12] != j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat5_1.append(j)
                j = j[:-1]
                k51 = j
            #T5.2
            elif (distance < 5000) and ((k52[5] != j[5]) or (k52[8] != j[8]) or
                                        (k52[9] != j[9]) or (k52[6] != j[6]) or
                                        (k52[7] != j[7]) or
                                        (k52[12] != j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat5_1.append(j)
                j = j[:-1]
                k52 = j
            #T5.3
            elif (distance < 10000) and (
                (k53[5] != j[5]) or (k53[8] != j[8]) or (k53[9] != j[9]) or
                (k53[6] != j[6]) or (k53[7] != j[7]) or (k53[12] != j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat5_1.append(j)
                j = j[:-1]
                k53 = j
            #T6
            elif ((k60[5] != j[5]) or (k60[8] != j[8]) or (k60[9] != j[9])
                  or (k60[6] != j[6]) or (k60[7] != j[7])
                  or (k60[12] != j[12])):

                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat6_0.append(j)
                j = j[:-1]
                k60 = j

    print("Tamaño de grupos:")

    print("distanciat000: " + str(len(distanciat000)))
    print("distanciat00: " + str(len(distanciat00)))
    print("distanciat0: " + str(len(distanciat0)))
    print("distanciat1: " + str(len(distanciat1)))
    print("distanciat2_1: " + str(len(distanciat2_1)))
    print("distanciat2_2: " + str(len(distanciat2_2)))
    print("distanciat3_1: " + str(len(distanciat3_1)))
    print("distanciat3_2: " + str(len(distanciat3_2)))
    print("distanciat4_1: " + str(len(distanciat4_1)))
    print("distanciat4_2: " + str(len(distanciat4_2)))
    print("distanciat5_1: " + str(len(distanciat5_1)))
    print("distanciat5_2: " + str(len(distanciat5_2)))
    print("distanciat5_3: " + str(len(distanciat5_3)))
    print("distanciat6_0: " + str(len(distanciat6_0)))

    t_actual = "AA+"
    g_actual = 1
    cota = 10

    if len(distanciat000) >= 6:
        distancia = distanciat000
    elif len(distanciat00 + distanciat000) >= 8:
        distancia = distanciat00 + distanciat000
        t_actual = "AA-"
        g_actual = 1
    elif len(distanciat0 + distanciat00 + distanciat000) >= cota:
        distancia = distanciat0 + distanciat00 + distanciat000
        t_actual = "A+"
        g_actual = 1
    elif len(distanciat1 + distanciat0 + distanciat00 + distanciat000) >= cota:
        distancia = distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "A-"
        g_actual = 2
    elif len(distanciat2_1 + distanciat1 + distanciat0 + distanciat00 +
             distanciat000) >= cota:
        distancia = distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "B+"
        g_actual = 3
    elif len(distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 +
             distanciat00 + distanciat000) >= cota:
        distancia = distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "B-"
        g_actual = 4
    elif len(distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 +
             distanciat0 + distanciat00 + distanciat000) >= cota:
        distancia = distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "C+"
        g_actual = 5
    elif len(distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 +
             distanciat1 + distanciat0 + distanciat00 + distanciat000) >= cota:
        distancia = distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "C-"
        g_actual = 6
    elif len(distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 +
             distanciat2_1 + distanciat1 + distanciat0 + distanciat00 +
             distanciat000) >= cota:
        distancia = distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "D+"
        g_actual = 7
    elif len(distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 +
             distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 +
             distanciat00 + distanciat000) >= 5:
        distancia = distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "D-"
        g_actual = 8
    elif len(distanciat5_1 + distanciat4_2 + distanciat4_1 + distanciat3_2 +
             distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 +
             distanciat0 + distanciat00 + distanciat000) >= 5:
        distancia = distanciat5_1 + distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "E+"
        g_actual = 9
        tasacionsimple = True
    elif len(distanciat5_2 + distanciat5_1 + distanciat4_2 + distanciat4_1 +
             distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 +
             distanciat1 + distanciat0 + distanciat00 + distanciat000) >= 5:
        distancia = distanciat5_2 + distanciat5_1 + distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "E-"
        g_actual = 10
        tasacionsimple = True
    elif len(distanciat5_3 + distanciat5_2 + distanciat5_1 + distanciat4_2 +
             distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 +
             distanciat2_1 + distanciat1 + distanciat0 + distanciat00 +
             distanciat000) >= 5:
        distancia = distanciat5_3 + distanciat5_2 + distanciat5_1 + distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "F+"
        g_actual = 11
        tasacionsimple = True
    elif len(distanciat6_0 + distanciat5_3 + distanciat5_2 + distanciat5_1 +
             distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 +
             distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 +
             distanciat00 + distanciat000) >= 5:
        distancia = distanciat6_0 + distanciat5_3 + distanciat5_2 + distanciat5_1 + distanciat4_2 + distanciat4_1 + distanciat3_2 + distanciat3_1 + distanciat2_2 + distanciat2_1 + distanciat1 + distanciat0 + distanciat00 + distanciat000
        t_actual = "F-"
        g_actual = 12
        tasacionsimple = True

    else:
        return 0, "N", 0, ["No hay links para tasación inválida",
                           ""], es_venta, 13

    distancias = sorted(distancia, key=lambda x: x[14])
    try:
        distancias = distancias[:20]
    except:
        distancias = distancia

    for dist in distancias:
        preciomt = dist[5] / ((dist[8] + dist[9]) / 2)
        dist.append(preciomt)

    preciosmts = [el[15] for el in distancias]

    med = stat.median(preciosmts)
    intermin = 0.4 * med
    intermax = 2.5 * med

    arregloaux = []

    for preciodistancia in distancias:
        if preciodistancia[15] < intermax and preciodistancia[15] > intermin:
            arregloaux.append(preciodistancia)

    print("mediana:" + str(med))
    print("intermin:" + str(intermin))
    print("intermax:" + str(intermax))
    print("Propiedades Eliminadas: " + str(len(distancias) - len(arregloaux)))
    distancias = arregloaux

    links = []
    for props in distancias:
        links.append(props[13])
    if tasacionsimple:
        preciosmts = [el[15] for el in distancias]
        prom = stat.mean(preciosmts)
        sup = (util + total) / 2
        price = sup * prom
        try:
            if es_venta:
                price = int(price / ufn)
            else:
                price = int(price)

            return (price, t_actual, len(distancias), links, es_venta,
                    g_actual)
        except:

            return (0, "N", len(distancias),
                    ["No hay links para tasación inválida", ""], es_venta, 13)

    y_train = []
    x_train = []

    for e in distancias:
        reg_terraza = (e[9] - e[8])
        reg_util = e[8]
        reg_dorms = e[6]
        reg_banos = e[7]
        reg_precio = e[5]
        reg_estacionamientos = e[12]
        x_train.append([
            reg_util, reg_terraza, reg_dorms, reg_banos, reg_estacionamientos,
            reg_util * reg_util, reg_util * reg_terraza, reg_util * reg_dorms,
            reg_util * reg_banos, reg_terraza * reg_terraza,
            reg_terraza * reg_dorms, reg_terraza * reg_banos,
            reg_dorms * reg_dorms, reg_dorms * reg_banos, reg_banos * reg_banos
        ])
        y_train.append(reg_precio)

    #y2_train=[]
    #y2_train.append(y_train)
    #y_train=y2_train
    x_train = np.array(x_train)
    y_train = np.array(y_train)

    x_test = [
        util, (total - util), dormitorios, banos, estacionamientos,
        util * util, util * (total - util), util * dormitorios, util * banos,
        (total - util) * (total - util), (total - util) * dormitorios,
        (total - util) * banos, dormitorios * dormitorios, dormitorios * banos,
        banos * banos
    ]
    x_test = np.array(x_test)
    x_test = np.transpose(x_test)
    # Make predictions using the testing set

    price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
        x_train, y_train, x_test)

    for dato in x_train:
        if utilnegativo:
            dato[0] = float(0.00000)
            dato[5] = float(0.00000)
            dato[6] = float(0.00000)
            dato[7] = float(0.00000)
            dato[8] = float(0.00000)

        if terrazanegativo:
            dato[1] = float(0.00000)
            dato[6] = float(0.00000)
            dato[9] = float(0.00000)
            dato[10] = float(0.00000)
            dato[11] = float(0.00000)

        if estacionamientosnegativo:
            dato[4] = float(0.0000)

    if utilnegativo or terrazanegativo or estacionamientosnegativo:
        price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
            x_train, y_train, x_test)

    try:
        if es_venta:
            price = int(price / ufn)
        else:
            price = int(price)
        return (price, t_actual, len(distancias), links, es_venta, g_actual)

    except:

        return (0, "N", len(distancias),
                ["No hay links para tasación inválida", ""], es_venta, 13)
예제 #9
0
import agentCreator
import time
import random
from bs4 import BeautifulSoup
import datetime
import pymysql as mysql
import uf


def error(link, texto):

    print("[PIVDM][ERROR] " + str(datetime.datetime.now()) + ',' + link + "," +
          str(texto))


uf = uf.getUf()

headers1 = {
    'authority':
    'www.portalinmobiliario.com',
    'cache-control':
    'max-age=0',
    'upgrade-insecure-requests':
    '1',
    'user-agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6)',
    'sec-fetch-mode':
    'navigate',
    'sec-fetch-user':
    '******',
    'accept':
past=datetime.date(past)
yesterday = datetime.now() - timedelta(days=30)
yesterday=datetime.date(yesterday)
from threading import Thread
from time import sleep
from datetime import datetime, timedelta
import pdfCreatorReportes as pdfC
import uf
import numpy as np
from sklearn import datasets, linear_model
import sendmail
import tasadorbot2 as tb2
import pubPortalExiste
import math

uf1=uf.getUf()

def rentaPProm(tipo,dormitorios,banos,estacionamientos,comuna):
    mariadb_connection = mysql.connect(user='******', password='******', host='127.0.0.1', database='bullestate')
    cur = mariadb_connection.cursor()
    sql = "SELECT (precio/metrosmin) FROM portalinmobiliario WHERE operacion='arriendo' and tipo='"+str(tipo)+"' and dormitorios='"+str(dormitorios)+"' and banos='"+str(banos)+"' and estacionamientos='"+str(estacionamientos)+"' and link like '%"+str(comuna)+"%'"
    cur.execute(sql)
    arriendo = cur.fetchall()
    cur = mariadb_connection.cursor()
    sql = "SELECT (precio/metrosmin) FROM portalinmobiliario WHERE operacion='venta' and dormitorios='"+str(dormitorios)+"' and banos='"+str(banos)+"' and estacionamientos='"+str(estacionamientos)+"' and link like '%"+str(comuna)+"%'"
    cur.execute(sql)
    venta = cur.fetchall()
    arriendo=sorted(arriendo)
    venta=sorted(venta)
    larriendo=len(arriendo)
    lventa=len(venta)
예제 #11
0
def calcularTasacion(operacion, region, tipo, lat, lon, util, total,
                     dormitorios, banos, estacionamientos):

    es_venta = operacion == "venta"
    print(es_venta)
    data = from_portalinmobiliario(operacion, tipo, region)
    distanciat0 = []
    distanciat1 = []
    distanciat2_1 = []
    distanciat2_2 = []
    distanciat3_1 = []
    distanciat3_2 = []
    distanciat4_1 = []
    distanciat4_2 = []
    k0 = [0] * 14
    k1 = [0] * 14
    k21 = [0] * 14
    k22 = [0] * 14
    k31 = [0] * 14
    k32 = [0] * 14
    k41 = [0] * 14
    k42 = [0] * 14
    print("1 corte")
    for j in data:
        # i3=op, i4=tipo, i5=precio, i6=dorms, i7=baños, i12= estacionamientos i8=util, i9=total
        if (j[1] > past) and (j[2] > yesterday) and (operacion
                                                     == j[3]) and (tipo
                                                                   == j[4]):
            lat1 = lat
            long1 = lon
            lat2 = j[10]
            long2 = j[11]
            r = 6371000
            c = pi / 180
            distance = 2 * r * asin(
                sqrt(
                    sin(c * (lat2 - lat1) / 2)**2 + cos(c * lat1) *
                    cos(c * lat2) * sin(c * (long2 - long1) / 2)**2))

            #T0
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.1) and (
                    abs(total / j[9] - 1) <
                    0.2) and (dormitorios == j[6]) and (banos == j[7]) and (
                        estacionamientos
                        == j[12]) and ((k0[5] != j[5]) or (k0[8] != j[8]) or
                                       (k0[9] != j[9]) or (k0[6] != j[6]) or
                                       (k0[7] != j[7]) or (k0[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat0.append(j)
                k0 = j
                j = j[:-1]

            #T1 REVISAR
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) <
                    0.4) and (dormitorios == j[6]) and (banos == j[7]) and (
                        estacionamientos
                        == j[12]) and ((k1[5] != j[5]) or (k1[8] != j[8]) or
                                       (k1[9] != j[9]) or (k1[6] != j[6]) or
                                       (k1[7] != j[7]) or (k1[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat1.append(j)
                j = j[:-1]
                k1 = j

            #T2.1
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) <
                    0.4) and (dormitorios == j[6]) and (banos == j[7]) and (
                        int(estacionamientos) >= (int(j[12]) - 1) and
                        (int(estacionamientos) <=
                         (int(j[12]) + 1))) and ((k21[5] != j[5]) or
                                                 (k21[8] != j[8]) or
                                                 (k21[9] != j[9]) or
                                                 (k21[6] != j[6]) or
                                                 (k21[7] != j[7]) or
                                                 (k21[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat2_1.append(j)
                j = j[:-1]
                k21 = j

            #T2.2
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) <
                    0.4) and (dormitorios == j[6]) and (banos == j[7]) and (
                        (k22[5] != j[5]) or (k22[8] != j[8]) or
                        (k22[9] != j[9]) or (k22[6] != j[6]) or
                        (k22[7] != j[7]) or (k22[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat2_2.append(j)
                j = j[:-1]
                k22 = j

            #T3.1
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) <
                    0.4) and (int(dormitorios) >= (int(j[6]) - 1) and
                              (int(dormitorios) <=
                               (int(j[6]) + 1))) and (banos == j[7]) and (
                                   (k31[5] != j[5]) or (k31[8] != j[8]) or
                                   (k31[9] != j[9]) or (k31[6] != j[6]) or
                                   (k31[7] != j[7]) or (k31[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat3_1.append(j)
                j = j[:-1]
                k31 = j

            #T3.2
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) < 0.4) and (banos == j[7]) and (
                        (k32[5] != j[5]) or (k32[8] != j[8]) or
                        (k32[9] != j[9]) or (k32[6] != j[6]) or
                        (k32[7] != j[7]) or (k32[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat3_2.append(j)
                j = j[:-1]
                k32 = j

            #T4.1
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) < 0.4) and (int(banos) >=
                                                      (int(j[7]) - 1) and
                                                      (int(banos) <=
                                                       (int(j[7]) + 1))) and (
                                                           (k41[5] != j[5]) or
                                                           (k41[8] != j[8]) or
                                                           (k41[9] != j[9]) or
                                                           (k41[6] != j[6]) or
                                                           (k41[7] != j[7]) or
                                                           (k41[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat4_1.append(j)
                j = j[:-1]
                k41 = j

            #T4.2
            if (distance < 1000) and (abs(util / j[8] - 1) < 0.2) and (
                    abs(total / j[9] - 1) < 0.4) and ((k42[5] != j[5]) or
                                                      (k42[8] != j[8]) or
                                                      (k42[9] != j[9]) or
                                                      (k42[6] != j[6]) or
                                                      (k42[7] != j[7]) or
                                                      (k42[12] != j[12])):
                d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                (100 * abs(util - j[8]))) +
                         (100 * abs(total - j[9]) * (100 * abs(total - j[9]))))
                j.append(d)
                distanciat4_2.append(j)
                j = j[:-1]
                k42 = j
    print("2 corte")

    t_actual = "A+"
    cota = 10

    if len(distanciat0) >= cota:
        distancia = distanciat0

    elif len(distanciat1) >= cota:
        distancia = distanciat1
        t_actual = "A-"
    elif len(distanciat2_1) >= cota:
        distancia = distanciat2_1
        t_actual = "B+"
    elif len(distanciat2_2) >= cota:
        distancia = distanciat2_2
        t_actual = "B-"
    elif len(distanciat3_1) >= cota:
        distancia = distanciat3_1
        t_actual = "C+"
    elif len(distanciat3_2) >= cota:
        distancia = distanciat3_2
        t_actual = "C-"
    elif len(distanciat4_1) >= cota:
        distancia = distanciat4_1
        t_actual = "D+"
    elif len(distanciat4_2) >= 5:
        distancia = distanciat4_2
        t_actual = "D-"

    else:
        return 0, "E", len(distanciat4_2), [], False
    print("t actual definido")
    distancias = sorted(distancia, key=lambda x: x[14])
    try:
        distancias = distancias[:40]
    except:
        distancias = distancia

    links = []
    for props in distancias:
        links.append(props[13])

    y_train = []
    x_train = []

    for e in distancias:
        reg_terraza = (e[9] - e[8])
        reg_util = e[8]
        reg_dorms = e[6]
        reg_banos = e[7]
        reg_precio = e[5]
        reg_estacionamientos = e[12]
        x_train.append([
            reg_util, reg_terraza, reg_dorms, reg_banos, reg_estacionamientos,
            reg_util * reg_util, reg_util * reg_terraza, reg_util * reg_dorms,
            reg_util * reg_banos, reg_terraza * reg_terraza,
            reg_terraza * reg_dorms, reg_terraza * reg_banos,
            reg_dorms * reg_dorms, reg_dorms * reg_banos, reg_banos * reg_banos
        ])
        y_train.append(reg_precio)

    #y2_train=[]
    #y2_train.append(y_train)
    #y_train=y2_train
    x_train = np.array(x_train)
    y_train = np.array(y_train)

    x_test = [
        util, (total - util), dormitorios, banos, estacionamientos,
        util * util, util * (total - util), util * dormitorios, util * banos,
        (total - util) * (total - util), (total - util) * dormitorios,
        (total - util) * banos, dormitorios * dormitorios, dormitorios * banos,
        banos * banos
    ]
    x_test = np.array(x_test)
    x_test = np.transpose(x_test)
    # Make predictions using the testing set

    price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
        x_train, y_train, x_test)

    for dato in x_train:
        if utilnegativo:
            dato[0] = float(0.00000)
            dato[5] = float(0.00000)
            dato[6] = float(0.00000)
            dato[7] = float(0.00000)
            dato[8] = float(0.00000)

        if terrazanegativo:
            dato[1] = float(0.00000)
            dato[6] = float(0.00000)
            dato[9] = float(0.00000)
            dato[10] = float(0.00000)
            dato[11] = float(0.00000)

        if estacionamientosnegativo:
            dato[4] = float(0.0000)

    if utilnegativo or terrazanegativo or estacionamientosnegativo:
        price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
            x_train, y_train, x_test)
    print("regresion hecha")
    try:
        if es_venta:
            price = int(price / uf.getUf())
        else:
            price = int(price)
        print(price, t_actual, len(distancias), links, es_venta)
        return (price, t_actual, len(distancias), links, es_venta)

    except:

        return -1, "ERROR", -1, [], False
def crearPdfFicha(fileName, id, propiedad, lenfotos, pro, datospro, interna,
                  datosinterna, regionP, links):
    #Propiedad:
    #DatosPro: Preciov/RentV/PrecioA/RentA, o bien solo PrecioA
    headerslocalizacion = []
    headerspropiedad = []
    headersrentabilidad = []
    headerscontacto = []
    datoslocalizacion = []
    datospropiedad = []
    datosrentabilidad = []
    datoscontacto = []

    if pro == "financiera":
        pro = True
        financiera = True
    else:
        financiera = False

    uf1 = uf.getUf()
    for x, p in enumerate(propiedad):
        if p is None:
            propiedad[x] = 0
    nombre = str(propiedad[0])
    region = str(propiedad[1])
    comuna = str(propiedad[14])
    operacion = str(propiedad[2])
    tipo = str(propiedad[3])

    headerslocalizacion.append("Operación")
    headerslocalizacion.append("Tipo de Prop.")
    headerslocalizacion.append("Región")
    headerslocalizacion.append("Comuna")

    datoslocalizacion.append(operacion.capitalize())
    datoslocalizacion.append(tipo.capitalize())
    datoslocalizacion.append(regionP.capitalize())
    datoslocalizacion.append(comuna.capitalize())

    precio = int(propiedad[4])
    precioreal = precio
    precioufreal = precio / uf1
    preciouf = (int(precio / uf1))
    preciouf = str(format(preciouf, ','))
    preciouf = preciouf.replace(',', '.')

    precio = str(format(precio, ','))
    precio = precio.replace(',', '.')

    dormitorios = str(int(propiedad[5]))
    banos = str(int(propiedad[6]))

    metrosmin = str(int(propiedad[7]))
    metrosmax = str(int(propiedad[8]))

    estacionamientos = str(int(propiedad[9]))
    bodegas = str(int(propiedad[10]))

    lat = str(propiedad[11])
    lon = str(propiedad[12])
    link = str(propiedad[13])

    headerspropiedad.append("Precio $")
    if operacion == 'venta':
        headerspropiedad.append("Precio UF")
    headerspropiedad.append("Sup. Util")
    headerspropiedad.append("Sup. Total")
    headerspropiedad.append("Dormitorios")
    headerspropiedad.append("Baños")
    headerspropiedad.append("Estacionamientos")
    headerspropiedad.append("Bodegas")

    datospropiedad.append(precio)
    if operacion == 'venta':
        datospropiedad.append(preciouf)
    datospropiedad.append(metrosmin)
    datospropiedad.append(metrosmax)
    datospropiedad.append(dormitorios)
    datospropiedad.append(banos)
    datospropiedad.append(estacionamientos)
    datospropiedad.append(bodegas)

    descripcion = propiedad[15]

    if pro:
        if operacion == 'venta':
            precioV = datospro[0]
            precioVreal = precioV
            precioV = precioV / uf1
            precioV = int(precioV)
            precioV = str(format(precioV, ','))
            precioV = precioV.replace(',', '.')
            precioV = 'UF ' + precioV
            rentV = float(datospro[1])
            rentV = int(rentV * 1000)
            rentV = float(rentV / 10)
            rentV = str(rentV) + "%"
            precioA = datospro[2]
            precioAreal = 10000 * (int(precioA / 10000))
            precioA = int(precioA)
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            rentA = float(datospro[3])
            rentA = int(rentA * 1000)
            rentA = float(rentA / 10)
            rentA = str(rentA) + "%"

            headersrentabilidad.append("Tasación Venta")
            headersrentabilidad.append("Rent. Venta")

            headersrentabilidad.append("Tasación Arriendo")
            headersrentabilidad.append("Rent. Arriendo")

            datosrentabilidad.append(precioV)
            datosrentabilidad.append(rentV)

            datosrentabilidad.append(precioA)
            datosrentabilidad.append(rentA)

        else:
            precioA = datospro[0]
            precioA = int(precioA[0])
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            headersrentabilidad.append("Tasación Arriendo")
            datosrentabilidad.append(precioA)

    if interna:
        mail = datosinterna[0]
        headerscontacto.append("Mail")
        datoscontacto.append(mail)

        telefono = datosinterna[1]
        headerscontacto.append("Telefono")
        if 'yapo' in link and telefono != 'NN':
            try:
                image = Image("auxphone.gif")
                image._restrictSize(1.2 * inch, 1.7 * inch)
                datoscontacto.append(image)
            except:
                datoscontacto.append('NN')
        else:
            datoscontacto.append(telefono)

        dueno = datosinterna[2]
        headerscontacto.append("Dueño")
        datoscontacto.append(dueno.capitalize())

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              leading=16))

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    tabla = []
    tabla.append(headerslocalizacion)
    tabla.append(datoslocalizacion)

    t1 = Table(tabla, hAlign='LEFT')
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    tabla = []
    tabla.append(headerspropiedad)
    tabla.append(datospropiedad)

    t2 = Table(tabla, hAlign='LEFT')
    t2.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 11),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    if pro:
        tabla = []
        tabla.append(headersrentabilidad)
        tabla.append(datosrentabilidad)

        t3 = Table(tabla, hAlign='LEFT')
        t3.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))
    if interna:
        tabla = []
        tabla.append(headerscontacto)
        tabla.append(datoscontacto)

        t4 = Table(tabla, hAlign='LEFT')
        t4.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

    try:
        image = Image('bull_logo2.png', hAlign='LEFT')
        image._restrictSize(2 * inch, 3 * inch)
        Story.append(image)
        Story.append(Spacer(1, 16))
    except:
        try:
            image = Image('bull_logo.jpg', hAlign='LEFT')
            image._restrictSize(2 * inch, 3 * inch)
            Story.append(image)
            Story.append(Spacer(1, 16))
        except:
            pass

    if interna:
        ptext = '<font size=11>FICHA PROPIEDAD: ' + str(id) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    else:
        ptext = '<font size=11>FICHA PROPIEDAD</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    Story.append(t1)
    Story.append(Spacer(1, 16))
    Story.append(t2)
    Story.append(Spacer(1, 16))
    if pro:
        Story.append(t3)
        Story.append(Spacer(1, 16))
    if interna:
        Story.append(t4)
        Story.append(Spacer(1, 16))

    ptext = '<font size=11>Descripción:</font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    if not interna:
        imagenDescripcion = Image('imagenDescripcion.png')
        Story.append(imagenDescripcion)
        Story.append(PageBreak())
    else:
        ptext = '<font size=11>' + str(descripcion) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(PageBreak())

    if len(links) > 0 and interna:
        print("entro en crear tabla de links")
        print(links)
        data = []
        n = 0
        headers = [
            "N°", "UF", "Precio", "UF/mt2", "MtsMin", "MtsMax", "Dorms",
            "Baños", "Link", "Disponibilidad"
        ]
        for l in links:
            if "portal" in l:
                d = []
                n += 1
                d.append(str(n))
                avaible = pubPortalExiste.publicacionExiste(l)
                id = botPropertyConnector.obtenerIdConLink(
                    l, "www.portalinmobiliario.com")
                id = id[0]
                prop = reportes.precio_from_portalinmobiliario(id)
                prop = prop[0]
                print("Arreglo de propiedad:")
                print(prop)
                print("1er dato de propiedad de propiedad:")
                print(prop[0])
                ufn = int(prop[0] / (uf.getUf()))
                d.append(ufn)
                d.append(prop[0])
                d.append((int(20 * ufn / (prop[1] + prop[2]))) / 10)
                d.append(int(prop[1]))
                d.append(int(prop[2]))
                d.append(prop[5])
                d.append(prop[6])
                print(d)
                print("appendeo bien datos")
                linkHtml = '<link href="' + l + '" color="blue">' + "Link" + '</link>'
                print(linkHtml)
                linkHtml = platypus.Paragraph(linkHtml, PS('body'))
                d.append(linkHtml)
                if avaible:
                    d.append("Disponible")
                else:
                    d.append("No disponible")
                print(str(n) + " intento de agregar prop a data")
                print(d)
                data.append(d)
            else:
                pass

        data = [headers] + data
        #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
        t = Table(data)
        t.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

        Story.append(t)
        Story.append(PageBreak())
    print("Antes de entrar a datos financieros")
    if pro and financiera and operacion == 'venta':

        print("entro datos financieros")
        tasacion = datospro[0]
        tasacionUF = (precioVreal / uf1)

        ftext = '<font size=11>Propuesta de Compra Arriendo y Posterior Venta en un Período de 7 Meses, ofertando 95% Valor propiedad, Revendiendo a 95%  del valor de tasación:</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        Story.append(Spacer(1, 14))
        rent = (
            1 +
            (((0.95 * tasacionUF - ((0.95) * precioufreal)) * 0.81 -
              ((0.95) * precioufreal) * 0.031) - 25 + precioAreal * 7 / uf1) /
            ((0.95) * precioufreal * 1.031 + 25) - 0.25 *
            ((((0.95 * tasacionUF - ((0.95) * precioufreal)) * 0.81 -
               ((0.95) * precioufreal) * 0.031) - 25 + precioAreal * 7 / uf1) /
             ((0.95) * precioufreal * 1.031 + 25) - 0.05))**(12 / 7) - 1
        data = [
            ["Item", "Valor"],
            [
                "Rent. de arriendo(1)",
                str(
                    int(1000 * (precioAreal * 12 / uf1 /
                                ((0.95) * precioufreal * 1.031 + 14))) / 10) +
                "%"
            ],
            [
                "Rent. Capital (2)",
                str(
                    int(1000 * (((0.95 * tasacionUF -
                                  ((0.95) * precioufreal)) * 0.81 -
                                 ((0.95) * precioufreal) * 0.031) - 14) /
                        ((0.95) * precioufreal * 1.031 + 14)) / 10) + "%"
            ],
            [
                "Rent. Total(3)",
                str(
                    int(1000 * (((0.95 * tasacionUF -
                                  ((0.95) * precioufreal)) * 0.81 -
                                 ((0.95) * precioufreal) * 0.031) - 14 +
                                precioAreal * 7 / uf1) /
                        ((0.95) * precioufreal * 1.031 + 14)) / 10) + "%"
            ],
            [
                "Rentabilidad Neta(4)",
                str(int(1000 * ((1 + rent)**(7 / 12) - 1)) / 10) + "%"
            ],
            [
                "Rentabilidad Neta UF (5)",
                str(
                    int(((int((0.95) * precioufreal * 1.031 + 25)) *
                         ((1 + rent)**(7 / 12) - 1)))) + " UF"
            ],
            ["Rentabilidad Anual Neta(6)",
             str(int(1000 * rent) / 10) + "%"], ["Costos Legales(7)", "25 UF"],
            [
                "Costos de Corretaje(8)",
                str(int(0.02 * 0.95 * precioufreal)) + " UF"
            ],
            [
                "IVA(9)",
                str(int((0.95 * tasacionUF -
                         ((0.95) * precioufreal)) * 0.19)) + " UF"
            ],
            [
                "Total Inversión Inicial(10)",
                str(int((0.95) * precioufreal * 1.031 + 25)) + " UF"
            ],
            [
                "Comisión BullEstate(11)",
                str(
                    int(0.25 * ((((0.95 * tasacionUF -
                                   ((0.95) * precioufreal)) * 0.81 -
                                  ((0.95) * precioufreal) * 0.031) - 25 +
                                 precioAreal * 7 / uf1) - 0.05 *
                                ((0.95) * precioufreal * 1.031 + 25)) +
                        0.01 * 0.95 * precioufreal)) + " UF"
            ]
        ]

        t = Table(data)
        table_style = (TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
        ]))
        t.setStyle(table_style)
        Story.append(t)
        Story.append(Spacer(1, 14))

        ftext = '<font size=6>(1)Rentabilidad calculada como doce veces el valor de arriendo dividido por el total de inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(2)Rentabilidad calculada como (valor de reventa - total inversión)/total inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(3)Rentabilidad de Arriendo + Rentabilidad de Capital, durante ciclo de inversión.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(4)Rentabilidad neta de un ciclo de inversión, descontando gastos.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(5)Rentabilidad neta en UF de un ciclo de inversión, descontando gastos.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(6)Rentabilidad neta anualizada</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(7)Estudio de títulos, pago de CBR y notaría.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(8)Valor correspondiente al 2% de costos de corretaje, al comprar propiedad</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(9) Valor correspondiente al 19% de la diferencia entre valor compra y valor re-venta</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(10) Valor propiedad más corretaje, gastos legales, y comisión Fija de Bullestate</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        ftext = '<font size=6>(11)Comisión correspondiente al 1% más un 25% de la utilidad obtenida sobre 5% por parte del Cliente.</font>'
        Story.append(Paragraph(ftext, styles["Justify"]))
        Story.append(Spacer(1, 14))
        Story.append(PageBreak())

        reventas = [0.9, 0.925, 0.95, 0.975, 1]

        for rev in reventas:
            ftext = '<font size=11>INFO FINANCIERA (Reventa al ' + (str(
                int(1000 * rev) / 10)).replace('.', ',') + '% - ' + str(
                    format(int(rev * tasacionUF), ',')).replace(
                        ',', '.') + ' UF - $' + str(
                            format(int(rev * tasacion), ',')).replace(
                                ',', '.') + ':</font>'

            Story.append(Paragraph(ftext, styles["Justify"]))
            Story.append(Spacer(1, 14))
            data = []
            headers = ["Valor UF:", "Valor Pesos", "% Oferta"]
            for i in range(1, 16):
                headers.append(str(i))

            for n in range(0, 9):
                row = []
                row.append(
                    (str(format(int((0.8 + 0.025 * n) * precioufreal),
                                ','))).replace(',', '.'))
                row.append(
                    (str(format(int((0.8 + 0.025 * n) * precioreal),
                                ','))).replace(',', '.'))
                row.append(str(80 + 2.5 * n) + "%")
                for i in range(1, 16):
                    tasacionUF = float(tasacionUF)
                    precioufreal = float(precioufreal)
                    precioAreal = float(precioAreal)
                    uf1 = float(uf1)
                    rev = float(rev)
                    rent = (1 + (((rev * tasacionUF -
                                   ((0.8 + 0.025 * n) * precioufreal)) * 0.81 -
                                  ((0.8 + 0.025 * n) * precioufreal) * 0.031) -
                                 25 + precioAreal * i / uf1) /
                            ((0.8 + 0.025 * n) * precioufreal * 1.031 + 25) -
                            0.25 *
                            ((((rev * tasacionUF -
                                ((0.8 + 0.025 * n) * precioufreal)) * 0.81 -
                               ((0.8 + 0.025 * n) * precioufreal) * 0.031) -
                              25 + precioAreal * i / uf1) /
                             ((0.8 + 0.025 * n) * precioufreal * 1.031 + 25) -
                             0.05))**(12 / i) - 1
                    rent = str((int(1000 * rent)) / 10) + "%"
                    row.append(rent)
                data.append(row)

            data = [headers] + data
            #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
            t = Table(data)
            table_style = (TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 6.5),
            ]))
            t.setStyle(table_style)
            for row, values, in enumerate(data):
                for column, value in enumerate(values):
                    try:
                        print(value)
                        intvalue = float(value[:-1])
                        print(intvalue)
                        if intvalue < 0:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.red)
                        if intvalue > 0.2:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.limegreen)
                        if intvalue > 0.5:
                            table_style.add('BACKGROUND', (column, row),
                                            (column, row), colors.darkgreen)
                    except:
                        pass
            Story.append(t)
            Story.append(Spacer(1, 14))
        Story.append(PageBreak())

    for x in range(0, lenfotos):

        image = Image(str(x) + " foto.jpg", hAlign='LEFT')
        image._restrictSize(6 * inch, 9 * inch)
        Story.append(image)
        Story.append(Spacer(1, 4))

    Story = list(Story)
    doc.build(Story)
예제 #13
0
def writeXlsx(file, data, columnnames, operacion):
    unf = uf.getUf()
    data = [list(elem) for elem in data]

    #creacion de precios, porcentajes y link
    for i, prop in enumerate(data):

        #arreglar precio
        precio = prop[1]

        #venta
        if operacion == "venta":
            precio = precio / unf
            precio = int(precio)
            prop[1] = precio

            if "Pr. Venta Tasado" in columnnames:
                index = columnnames.index("Pr. Venta Tasado")
                precio2 = prop[index] / unf
                precio2 = int(precio2)
                prop[index] = precio2

        #arriendo
        else:

            if "Pr. Arriendo Tasado" in columnnames:
                index = columnnames.index("Pr. Arriendo Tasado")
                precio2 = int(prop[index])
                prop[index] = precio2

        #quitar decimales a valores
        if "Utiles" in columnnames:
            index = columnnames.index("Utiles")
            prop[index] = int(prop[index])

        if "Total" in columnnames:
            index = columnnames.index("Total")
            prop[index] = int(prop[index])

        if "Estac." in columnnames:
            index = columnnames.index("Estac.")
            prop[index] = int(prop[index])

        if "Bod." in columnnames:
            index = columnnames.index("Bod.")
            prop[index] = int(prop[index])

        if "Dist metro" in columnnames:
            index = columnnames.index("Dist metro")
            prop[index] = int(prop[index])

    # Create a workbook and add a worksheet.
    workbook = xlsxwriter.Workbook(file)
    worksheet = workbook.add_worksheet()

    # Add a bold format to use to highlight cells.
    bold = workbook.add_format({'bold': True})

    # Add a number format for cells with money.
    money = workbook.add_format({'num_format': '$#,##0'})

    # Add a number format for cells with percentage
    perc = workbook.add_format({'num_format': '0.0%'})

    # Add a date format
    date = workbook.add_format({'num_format': 'dd/mm/yy'})

    # Write some data headers.
    worksheet.write_row(row=0, col=0, data=columnnames, cell_format=bold)

    #encontrar indices
    index_r_v = columnnames.index(
        "Rent. Venta") if "Rent. Venta" in columnnames else -1
    index_r_a = columnnames.index(
        "Rent. Arriendo") if "Rent. Arriendo" in columnnames else -1

    index_precio = columnnames.index(
        "Precio") if "Precio" in columnnames else -1
    index_precio_a_t = columnnames.index(
        "Pr. Arriendo Tasado") if "Pr. Arriendo Tasado" in columnnames else -1
    index_fecha_e = columnnames.index(
        "fecha encontrado") if "fecha encontrado" in columnnames else -1
    index_metro = columnnames.index("Metro") if "Metro" in columnnames else -1
    index_link = columnnames.index("Link") if "Link" in columnnames else -1
    index_mail = columnnames.index("Mail") if "Mail" in columnnames else -1
    index_tel = columnnames.index(
        "Telefono") if "Telefono" in columnnames else -1
    index_obs = columnnames.index(
        "Observaciones") if "Observaciones" in columnnames else -1

    #ancho de columnas
    length_list = [len(x) for x in columnnames]
    for i, width in enumerate(length_list):
        worksheet.set_column(i, i, width + 2)
    if index_metro != -1:
        worksheet.set_column(index_metro, index_metro, 15)
    if index_link != -1:
        worksheet.set_column(index_link, index_link, 10)
    if index_mail != -1:
        worksheet.set_column(index_mail, index_mail, 30)
    if index_tel != -1:
        worksheet.set_column(index_tel, index_tel, 15)
    if index_obs != -1:
        worksheet.set_column(index_obs, index_obs, 50)

    # Iterate over the data and write it out row by row.
    for i, c in enumerate(data):
        for j, f in enumerate(c):
            #caso rentabilidad venta y arriendo
            if j == index_r_v:
                worksheet.write(i + 1, j, f, perc)
            elif j == index_r_a:
                worksheet.write(i + 1, j, f, perc)

            #caso precios
            elif j == index_precio and operacion == "arriendo":
                worksheet.write(i + 1, j, f, money)
            elif j == index_precio_a_t:
                worksheet.write(i + 1, j, f, money)

            #caso fechas
            elif j == index_fecha_e:
                worksheet.write(i + 1, j, f, date)

            else:
                worksheet.write(i + 1, j, f)

    print('xlsx creado')
    workbook.close()
import tasadorv2
import reportes
import uf
import random
ufn = uf.getUf()
tipo = "departamento"

comunas = ['las condes']
count = 0
deltaprice = []

data = reportes.from_portalinmobiliario(tipo, "metropolitana", comunas, False)
datalen = len(data)

ponds = [0.1, 0.5, 1, 1.5, 2, 2.5, 5, 10]
results = []

for pd in ponds:
    for prop in data:
        count += 1
        #print(prop[3], prop[4], prop[10], prop[11], prop[8], prop[9], prop[6], prop[7], prop[12])
        precio, confianza, nrProps, links, venta, g = tasadorv2.calcularTasacionData(
            prop[3], prop[4], prop[10], prop[11], prop[8], prop[9], prop[6],
            prop[7], prop[12], data, pd)
        #print(precio)
        realprice = prop[5] / ufn
        difprice = abs(realprice - precio) / realprice
        array = []
        array.append(difprice)
        array.append(nrProps)
        array.append(confianza)
def crearPdfFicha(fileName, id, propiedad, lenfotos, pro, datospro, interna,
                  datosinterna, regionP, links):
    #Propiedad:
    #DatosPro: Preciov/RentV/PrecioA/RentA, o bien solo PrecioA
    headerslocalizacion = []
    headerspropiedad = []
    headersrentabilidad = []
    headerscontacto = []
    datoslocalizacion = []
    datospropiedad = []
    datosrentabilidad = []
    datoscontacto = []

    uf1 = uf.getUf()
    for x, p in enumerate(propiedad):
        if p is None:
            propiedad[x] = 0
    nombre = str(propiedad[0])
    region = str(propiedad[1])
    comuna = str(propiedad[14])
    operacion = str(propiedad[2])
    tipo = str(propiedad[3])

    headerslocalizacion.append("Operación")
    headerslocalizacion.append("Tipo de Prop.")
    headerslocalizacion.append("Región")
    headerslocalizacion.append("Comuna")

    datoslocalizacion.append(operacion.capitalize())
    datoslocalizacion.append(tipo.capitalize())
    datoslocalizacion.append(regionP.capitalize())
    datoslocalizacion.append(comuna.capitalize())

    precio = int(propiedad[4])

    preciouf = (int(precio / uf1))
    preciouf = str(format(preciouf, ','))
    preciouf = preciouf.replace(',', '.')

    precio = str(format(precio, ','))
    precio = precio.replace(',', '.')

    dormitorios = str(int(propiedad[5]))
    banos = str(int(propiedad[6]))

    metrosmin = str(int(propiedad[7]))
    metrosmax = str(int(propiedad[8]))

    estacionamientos = str(int(propiedad[9]))
    bodegas = str(int(propiedad[10]))

    lat = str(propiedad[11])
    lon = str(propiedad[12])
    link = str(propiedad[13])

    headerspropiedad.append("Precio $")
    if operacion == 'venta':
        headerspropiedad.append("Precio UF")
    headerspropiedad.append("Sup. Util")
    headerspropiedad.append("Sup. Total")
    headerspropiedad.append("Dormitorios")
    headerspropiedad.append("Baños")
    headerspropiedad.append("Estacionamientos")
    headerspropiedad.append("Bodegas")

    datospropiedad.append(precio)
    if operacion == 'venta':
        datospropiedad.append(preciouf)
    datospropiedad.append(metrosmin)
    datospropiedad.append(metrosmax)
    datospropiedad.append(dormitorios)
    datospropiedad.append(banos)
    datospropiedad.append(estacionamientos)
    datospropiedad.append(bodegas)

    descripcion = propiedad[15]

    if pro:
        if operacion == 'venta':
            precioV = datospro[0]
            precioV = precioV / uf1
            precioV = int(precioV)
            precioV = str(format(precioV, ','))
            precioV = precioV.replace(',', '.')
            precioV = 'UF ' + precioV
            rentV = float(datospro[1])
            rentV = int(rentV * 1000)
            rentV = float(rentV / 10)
            rentV = str(rentV) + "%"
            precioA = datospro[2]
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            rentA = float(datospro[3])
            rentA = int(rentA * 1000)
            rentA = float(rentA / 10)
            rentA = str(rentA) + "%"

            headersrentabilidad.append("Tasación Venta")
            headersrentabilidad.append("Rent. Venta")

            headersrentabilidad.append("Tasación Arriendo")
            headersrentabilidad.append("Rent. Arriendo")

            datosrentabilidad.append(precioV)
            datosrentabilidad.append(rentV)

            datosrentabilidad.append(precioA)
            datosrentabilidad.append(rentA)

        else:
            precioA = datospro[0]
            precioA = str(format(precioA, ','))
            precioA = precioA.replace(',', '.')
            precioA = '$ ' + precioA
            headersrentabilidad.append("Tasación Arriendo")
            datosrentabilidad.append(precioA)

    if interna:
        mail = datosinterna[0]
        headerscontacto.append("Mail")
        datoscontacto.append(mail)

        telefono = datosinterna[1]
        headerscontacto.append("Telefono")
        if 'yapo' in link and telefono != 'NN':
            try:
                image = Image("auxphone.gif")
                image._restrictSize(1.2 * inch, 1.7 * inch)
                datoscontacto.append(image)
            except:
                datoscontacto.append('NN')
        else:
            datoscontacto.append(telefono)

        dueno = datosinterna[2]
        headerscontacto.append("Dueño")
        datoscontacto.append(dueno.capitalize())

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              leading=16))

    doc = SimpleDocTemplate(fileName,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)

    Story = []

    tabla = []
    tabla.append(headerslocalizacion)
    tabla.append(datoslocalizacion)

    t1 = Table(tabla, hAlign='LEFT')
    t1.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#34BAAF')),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    tabla = []
    tabla.append(headerspropiedad)
    tabla.append(datospropiedad)

    t2 = Table(tabla, hAlign='LEFT')
    t2.setStyle(
        TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 11),
            ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
            ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
        ]))
    if pro:
        tabla = []
        tabla.append(headersrentabilidad)
        tabla.append(datosrentabilidad)

        t3 = Table(tabla, hAlign='LEFT')
        t3.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))
    if interna:
        tabla = []
        tabla.append(headerscontacto)
        tabla.append(datoscontacto)

        t4 = Table(tabla, hAlign='LEFT')
        t4.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 11),
            ]))

    image = Image('bull_logo2.png', hAlign='LEFT')
    image._restrictSize(2 * inch, 3 * inch)
    Story.append(image)
    Story.append(Spacer(1, 16))

    if interna:
        ptext = '<font size=11><b>FICHA PROPIEDAD</b>: ' + str(id) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    else:
        ptext = '<font size=11><b>FICHA PROPIEDAD</b></font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(Spacer(1, 14))

    Story.append(t1)
    Story.append(Spacer(1, 16))
    Story.append(t2)
    Story.append(Spacer(1, 16))
    if pro:
        Story.append(t3)
        Story.append(Spacer(1, 16))
    if interna:
        Story.append(t4)
        Story.append(Spacer(1, 16))

    ptext = '<font size=11><b>Descripción:</b></font>'
    Story.append(Paragraph(ptext, styles["Justify"]))
    Story.append(Spacer(1, 12))

    if not interna:
        imagenDescripcion = Image('imagenDescripcion.png')
        Story.append(imagenDescripcion)
        Story.append(PageBreak())
    else:
        ptext = '<font size=11>' + str(descripcion) + '</font>'
        Story.append(Paragraph(ptext, styles["Justify"]))
        Story.append(PageBreak())

    if len(links) > 0 and interna:
        print("entro en crear tabla de links")
        print(links)
        data = []
        n = 0
        headers = [
            "N°", "UF", "Precio", "UF/mt2", "MtsMin", "MtsMax", "Dorms",
            "Baños", "Link", "Disponibilidad"
        ]
        for l in links:
            if "portal" in l:
                d = []
                n += 1
                d.append(str(n))
                avaible = pubPortalExiste.publicacionExiste(l)
                id = botPropertyConnector.obtenerIdConLink(
                    l, "www.portalinmobiliario.com")
                id = id[0]
                prop = reportes.precio_from_portalinmobiliario(id)
                prop = prop[0]
                print("Arreglo de propiedad:")
                print(prop)
                print("1er dato de propiedad de propiedad:")
                print(prop[0])
                ufn = int(prop[0] / (uf.getUf()))
                d.append(ufn)
                d.append(prop[0])
                d.append((int(20 * ufn / (prop[1] + prop[2]))) / 10)
                d.append(int(prop[1]))
                d.append(int(prop[2]))
                d.append(prop[5])
                d.append(prop[6])
                print(d)
                print("appendeo bien datos")
                linkHtml = '<link href="' + l + '" color="blue">' + "Link" + '</link>'
                print(linkHtml)
                linkHtml = platypus.Paragraph(linkHtml, PS('body'))
                d.append(linkHtml)
                if avaible:
                    d.append("Disponible")
                else:
                    d.append("No disponible")
                print(str(n) + " intento de agregar prop a data")
                print(d)
                data.append(d)
            else:
                pass

        data = [headers] + data
        #t=Table(data,nrCols*[0.6*inch], nrRows*[0.25*inch])
        t = Table(data)
        t.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONTSIZE', (0, 0), (-1, -1), 9),
            ]))

        Story.append(t)
        Story.append(PageBreak())

    for x in range(0, lenfotos):

        image = Image(str(x) + " foto.jpg", hAlign='LEFT')
        image._restrictSize(6 * inch, 9 * inch)
        Story.append(image)
        Story.append(Spacer(1, 4))

    Story = list(Story)
    doc.build(Story)
예제 #16
0
def calcularTasacionData(operacion, tipo, lat, lon, util, total, dormitorios,
                         banos, estacionamientos, data, pondDist):

    ufn = uf.getUf()
    es_venta = operacion == "venta"

    #Generar Regresion General con datos:

    y_train = []
    x_train = []

    #Data=id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link
    for prop in data:
        reg_total = prop[9]
        reg_util = prop[8]
        reg_dorms = prop[6]
        reg_banos = prop[7]
        reg_precio = prop[5]
        reg_estacionamientos = prop[12]
        x_train.append(
            [reg_util, reg_total, reg_dorms, reg_banos, reg_estacionamientos])
        y_train.append(reg_precio)

    # y2_train=[]
    # y2_train.append(y_train)
    # y_train=y2_train
    x_train = np.array(x_train)
    y_train = np.array(y_train)

    x_test = [util, total, dormitorios, banos, estacionamientos]
    x_test = np.array(x_test)
    x_test = np.transpose(x_test)
    # Make predictions using the testing set

    p, utilnegativo, terrazanegativo, estacionamientosnegativo, coef = regresion(
        x_train, y_train, x_test)

    #print("Regresion Hecha")

    #print(coef)
    promcoef = sum(abs(coef)) / len(coef)
    matrix = []
    data = sorted(data, key=lambda x: x[5])
    count = 0
    #Data=id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link
    for j in data:
        # i3=op, i4=tipo, i5=precio, i6=dorms, i7=baños, i12= estacionamientos i8=util, i9=total
        if (j[1] > past) and (j[2] > yesterday) and (operacion
                                                     == j[3]) and (tipo
                                                                   == j[4]):
            count += 1
            lat1 = lat
            long1 = lon
            lat2 = j[10]
            long2 = j[11]
            r = 6371000
            c = pi / 180
            distance = 2 * r * asin(
                sqrt(
                    sin(c * (lat2 - lat1) / 2)**2 + cos(c * lat1) *
                    cos(c * lat2) * sin(c * (long2 - long1) / 2)**2))
            distance2 = ((pondDist * promcoef * distance)**2 +
                         (coef[0] * (j[8] - util))**2 +
                         (coef[1] * (j[9] - util))**2 + (coef[2] *
                                                         (j[6] - util))**2 +
                         (coef[3] * (j[7] - util))**2 + (coef[4] *
                                                         (j[12] - util))**2)
            if len(j) == 14:
                j.append(distance2)
            else:
                j[14] = distance2
            matrix.append(j)

    matrix = sorted(matrix, key=lambda x: x[14])
    links = []
    totalDistance = 0
    count = 0
    totalPrice = 0
    totalAntiDistance = 0
    lastDistance = 0
    for m in matrix:
        count += 1
        mprom = (m[8] + m[9]) / 2
        totalDistance += m[14]
        totalAntiDistance += 1 / m[14]
        totalPrice += m[5] / (m[14] * mprom)
        links.append(m[13])

        if count > 10 and (m[14] - lastDistance) > (m[14] / count):
            break
        lastDistance = m[14]
    price = totalPrice / totalAntiDistance
    price = price * ((util + total) / 2)

    try:
        if es_venta:
            price = int(price / ufn)
        else:
            price = int(price)
        return (price, totalDistance, count, links, es_venta, 1)

    except:

        return (0, "N", count, ["No hay links para tasación inválida",
                                ""], es_venta, 13)
예제 #17
0
def calcularTasacionData(operacion, tipo, lat, lon, util, total, dormitorios,
                         banos, estacionamientos, data):
    ufn = uf.getUf()
    es_venta = operacion == "venta"
    distanciasDict = {}
    confDict = {
        0: 100,
        1: 97,
        2: 95,
        3: 92,
        4: 90,
        5: 80,
        6: 70,
        7: 60,
        8: 50,
        9: 40,
        10: 30,
        11: 20,
        12: 15,
        13: 10,
        14: 7,
        15: 5,
        16: 2,
        17: 0
    }

    tasacionsimple = False

    kDict = {}

    drange = [
        50, 100, 200, 500, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000,
        1000, 5000, 10000, 5000000
    ]
    utilrange = [
        0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 1000000,
        1000000, 1000000, 1000000
    ]
    dormrange = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 100, 100, 100, 100, 100, 100]
    bathrange = [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 100, 100, 100, 100, 100]
    parkingrange = [
        0, 0, 0, 0, 0, 0, 1, 100, 100, 100, 100, 100, 100, 100, 100, 100
    ]

    auxparkingbool = False
    #Aux dictionaries for different parkings
    auxDict1 = {}
    auxDict2 = {}

    try:

        if estacionamientos == 0:
            auxparking1 = 1
            auxparking2 = 2
        if estacionamientos == 1:
            auxparking1 = 1
            auxparking2 = 2
        else:
            auxparking1 = estacionamientos - 2
            auxparking2 = estacionamientos - 1
        auxparkingbool = True
    except:
        pass

    data = sorted(data, key=lambda x: x[5])

    for j in data:
        # i3=op, i4=tipo, i5=precio, i6=dorms, i7=baños, i12= estacionamientos i8=util, i9=total
        if (j[1] > past) and (j[2] > yesterday) and (operacion
                                                     == j[3]) and (tipo
                                                                   == j[4]):
            lat1 = lat
            long1 = lon
            lat2 = j[10]
            long2 = j[11]
            r = 6371000
            c = pi / 180
            distance = 2 * r * asin(
                sqrt(
                    sin(c * (lat2 - lat1) / 2)**2 + cos(c * lat1) *
                    cos(c * lat2) * sin(c * (long2 - long1) / 2)**2))
            if tipo in 'local comercial':
                dormitorios = 0
                banos = 0
                estacionamientos = 0
                j[6] = 0
                j[7] = 0
                j[12] = 0
            for x in range(0, 16):

                kDict[x] = [0] * 16
                if (distance < drange[x]) and (abs(util/j[8]-1)<utilrange[x]) and (abs(total/j[9]-1)<(1.5*utilrange[x])) and \
                        (abs(dormitorios-j[6])<=dormrange[x] or tipo=="comercial") and (abs(banos-j[7])<=bathrange[x]or tipo=="comercial") and \
                        ((kDict[x][5]!=j[5]) or (kDict[x][8]!=j[8]) or (kDict[x][9]!=j[9]) or (kDict[x][6]!=j[6]) or (kDict[x][7]!=j[7]) or (kDict[x][12]!=j[12])):

                    d = sqrt(distance * distance + (100 * abs(util - j[8]) *
                                                    (100 * abs(util - j[8]))) +
                             (100 * abs(total - j[9]) *
                              (100 * abs(total - j[9]))))
                    j.append(d)
                    if x not in distanciasDict:
                        distanciasDict[x] = []
                        #print("creada la entrada para el valor:"+str(x))
                        if auxparkingbool:
                            auxDict1[x] = []
                            auxDict2[x] = []

                    if ((abs(estacionamientos - j[12]) <= parkingrange[x])
                            or tipo == "casa" or tipo == "comercial"):
                        distanciasDict[x].append(j)
                    if x < 4:
                        if (auxparkingbool
                                and (j[12] - estacionamientos) == -1):
                            auxDict1[x].append(j)
                        if (auxparkingbool
                                and (j[12] - estacionamientos) == 1):
                            auxDict2[x].append(j)
                    kDict[x] = j

                    break

    print("Tamaño de grupos:")
    for x in range(0, 16):
        if x in distanciasDict:
            print(str(x) + ": " + str(len(distanciasDict[x])))
    cota = 5
    distancia = []
    distanciaaux = []
    auxdistancia1 = []
    auxdistancia2 = []

    g_actual = 0
    for x in range(0, 16):
        if x == 1:
            cota += 1
        if x == 2:
            cota += 1
        g_actual = x
        if x >= 10:
            tasacionsimple = True
        if x in distanciasDict:
            distancia += distanciasDict[x]

            for dist in distancia:
                preciomt = dist[5] / ((dist[8] + dist[9]) / 2)
                dist.append(preciomt)

                preciosmts = [el[15] for el in distancia]

                med = stat.median(preciosmts)
                intermin = 0.5 * med
                intermax = 2 * med

                arregloaux = []

                for preciodistancia in distancia:
                    if preciodistancia[15] < intermax and preciodistancia[
                            15] > intermin:
                        arregloaux.append(preciodistancia)

                print("mediana:" + str(med))
                print("intermin:" + str(intermin))
                print("intermax:" + str(intermax))
                print("Propiedades Eliminadas: " +
                      str(len(distancia) - len(arregloaux)))
                distancia = arregloaux

            if x < 4:
                auxdistancia1 += auxDict1[x]
                auxdistancia2 += auxDict2[x]
            if len(distancia) >= cota:
                distancia = sorted(distancia, key=lambda x: x[5])
                for a in range(0, len(distancia) - 1):
                    if (distancia[a][5] == distancia[a + 1][5]
                            and distancia[a][6] == distancia[a + 1][6]
                            and distancia[a][7] == distancia[a + 1][7]
                            and distancia[a][12] == distancia[a + 1][12]
                            and abs(distancia[a][8] - distancia[a + 1][8]) <= 2
                            and abs(distancia[a][9] - distancia[a + 1][9]) <= 2
                        ) and len(distancia) > 1:
                        pass
                    else:
                        distanciaaux.append(distancia[a])

                distancia = distanciaaux
                #opcion de marcar repetidos, o sacarlos de la matriz y no considerarlos en la tasacion
                if len(distancia) >= cota:

                    if x < 4:

                        if len(auxdistancia1) >= cota:

                            auxdistancia1 = sorted(auxdistancia1,
                                                   key=lambda x: x[5])
                            auxcota = 0
                            if len(auxdistancia1) > 1:
                                for a in range(0, len(auxdistancia1) - 1):
                                    print(a)
                                    print(auxdistancia1[a])
                                    if (auxdistancia1[a][5]
                                            == auxdistancia1[a + 1][5]
                                            and auxdistancia1[a][6]
                                            == auxdistancia1[a + 1][6]
                                            and auxdistancia1[a][7]
                                            == auxdistancia1[a + 1][7]
                                            and auxdistancia1[a][12]
                                            == auxdistancia1[a + 1][12] and
                                            abs(auxdistancia1[a][8] -
                                                auxdistancia1[a + 1][8]) <= 2
                                            and
                                            abs(auxdistancia1[a][9] -
                                                auxdistancia1[a + 1][9]) <= 2):
                                        auxcota += 1
                                if (len(auxdistancia1) - auxcota >= cota):
                                    print(
                                        'Datos con un estacionamiento menos: '
                                        + str(len(auxdistancia1)))
                                    print(
                                        'precio y estacionamientos con un estacionamiento menos: '
                                        + str([el[5]
                                               for el in auxdistancia1]) +
                                        '-' +
                                        str([el[12] for el in auxdistancia1]))
                                    distancia += auxdistancia1

                        if len(auxdistancia2) >= cota:

                            auxdistancia2 = sorted(auxdistancia2,
                                                   key=lambda x: x[5])
                            auxcota = 0
                            if len(auxdistancia2) > 1:
                                for a in range(0, len(auxdistancia2) - 1):
                                    if (auxdistancia2[a][5]
                                            == auxdistancia2[a + 1][5]
                                            and auxdistancia2[a][6]
                                            == auxdistancia2[a + 1][6]
                                            and auxdistancia2[a][7]
                                            == auxdistancia2[a + 1][7]
                                            and auxdistancia2[a][12]
                                            == auxdistancia2[a + 1][12] and
                                            abs(auxdistancia2[a][8] -
                                                auxdistancia2[a + 1][8]) <= 2
                                            and
                                            abs(auxdistancia2[a][9] -
                                                auxdistancia2[a + 1][9]) <= 2):
                                        auxcota += 1
                            if len(auxdistancia2) - auxcota >= cota:
                                #print('Datos con un estacionamiento mas: ' + str(len(auxdistancia2)))
                                #print('precio y estacionamientos con un estacionamiento mas: '+str([el[5] for el in auxdistancia1])+'-'  + str([el[12] for el in auxdistancia2]))
                                distancia += auxdistancia2

                    print('grupo Resultante: ' + str(x))
                    break

    if len(distancia) < cota:
        return (0, 0, len(distancia), "No links to show", es_venta, 17)

    distancias = sorted(distancia, key=lambda x: x[14])
    try:
        distancias = distancias[:10]
    except:
        pass

    #esto hay q hacerlo antes de sacar la cota

    print('Datos Finales: ' + str(len(distancias)))
    print('precio y estacionamientos Finales: ' +
          str([el[5] / ufn for el in distancias]) + '-' +
          str([el[12] for el in distancias]))
    print('IDS Finales: ' + str(sorted([el[0] for el in distancias])))

    links = []
    for props in distancias:
        links.append(props[13])
    if tasacionsimple:
        preciosmts = [el[15] for el in distancias]
        prom = stat.mean(preciosmts)
        sup = (util + total) / 2
        price = sup * prom
        try:
            if es_venta:
                price = int(price / ufn)
            else:
                price = int(price)

            return (price, confDict[g_actual], len(distancias), links,
                    es_venta, g_actual)
        except:
            print("Entro al except 1")
            return (0, 0, len(distancias),
                    ["No hay links para tasación inválida", ""], es_venta, 17)

    y_train = []
    x_train = []

    for e in distancias:
        reg_terraza = (e[9] - e[8])
        reg_util = e[8]
        reg_dorms = e[6]
        reg_banos = e[7]
        reg_precio = e[5]
        reg_estacionamientos = e[12]
        # x_train.append([reg_util,reg_terraza,reg_dorms,reg_banos,reg_estacionamientos,reg_util*reg_util,
        #                 reg_util*reg_terraza,reg_util*reg_dorms,reg_util*reg_banos,reg_terraza*reg_terraza,reg_terraza*reg_dorms,
        #                 reg_terraza*reg_banos,reg_dorms*reg_dorms,reg_dorms*reg_banos,reg_banos*reg_banos])
        x_train.append([
            reg_util, reg_terraza, reg_dorms, reg_banos, reg_estacionamientos,
            reg_util * reg_dorms, reg_util * reg_banos, reg_dorms * reg_dorms,
            reg_dorms * reg_banos, reg_banos * reg_banos
        ])
        y_train.append(reg_precio)

    #y2_train=[]
    #y2_train.append(y_train)
    #y_train=y2_train
    x_train = np.array(x_train)
    y_train = np.array(y_train)

    # x_test = [util,(total-util),dormitorios,banos,estacionamientos,
    #           util*util,util*(total-util),util*dormitorios,util*banos,
    #           (total-util)*(total-util),(total-util)*dormitorios,(total-util)*banos,
    #           dormitorios*dormitorios,dormitorios*banos,banos*banos]
    x_test = [
        util, (total - util), dormitorios, banos, estacionamientos,
        util * dormitorios, util * banos, dormitorios * dormitorios,
        dormitorios * banos, banos * banos
    ]
    x_test = np.array(x_test)
    x_test = np.transpose(x_test)
    # Make predictions using the testing set

    price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
        x_train, y_train, x_test)

    for dato in x_train:
        if utilnegativo:
            dato[0] = float(0.00000)
            # dato[5] = float(0.00000)
            # dato[6] = float(0.00000)
            # dato[7] = float(0.00000)
            # dato[8] = float(0.00000)

        if terrazanegativo:
            dato[1] = float(0.00000)
            # dato[6]=float(0.00000)
            # dato[9]=float(0.00000)
            # dato[10]=float(0.00000)
            # dato[11]=float(0.00000)

        if estacionamientosnegativo:
            dato[4] = float(0.0000)

    if utilnegativo or terrazanegativo or estacionamientosnegativo:
        price, utilnegativo, terrazanegativo, estacionamientosnegativo = regresion(
            x_train, y_train, x_test)
    try:
        if es_venta:
            price = int(price / ufn)

        else:
            price = int(price)
        if price > 0:
            print("Check")
            print(price)
            return (price, confDict[g_actual], len(distancias), links,
                    es_venta, g_actual)
        else:
            return (0, "N", len(distancias),
                    ["No hay links para tasación inválida", ""], es_venta, 13)

    except:
        print("Entro al except 2")
        print(price)
        return (0, "N", len(distancias),
                ["No hay links para tasación inválida", ""], es_venta, 13)
예제 #18
0
def crearFicha(sitio, id, mail, tipoficha):
    links = []
    text2 = ''
    auxPhone = 0
    #Determinar tipo de informe
    pro = False
    interna = False
    financiera = False
    textmail = ''
    ufn = uf.getUf()
    if tipoficha > 4:
        financiera = True
        tipoficha = tipoficha - 4
    if tipoficha == 2:
        pro = True
    elif tipoficha == 3:
        interna = True
    elif tipoficha == 4:
        interna = True
        pro = True

    #Chequear que sitio este bien
    sitio = sitio.lower()

    if ('portal' in sitio):
        sitio = 'portal'
    elif ('yapo' in sitio):
        sitio = 'yapo'
    else:
        text = 'Sitio ingresado es incorrecto. Favor ingresar portalinmobiliario o yapo.'
        return (text)
    #Chequear que mail este bien
    if ('@' not in mail):
        text = 'Email incorrecto. Favor ingresar correo válido.'
        return (text)
    if ('.' not in mail):
        text = 'Email incorrecto. Favor ingresar correo válido.'
        return (text)

    #sacar informacion de bbdd, y chequear que propiedad existe:
    propiedad = obtenerProp(id, sitio)
    print(propiedad)

    if len(propiedad) < 1:

        if sitio == 'portal':
            link = "https://www.portalinmobiliario.com/" + str(id)
        else:
            link = "https://www.yapo.cl/region_metropolitana/" + str(id)

        if not pubPortalExiste.publicacionExiste(
                link) and not pubYapoExiste.publicacionExiste(link):
            text = '¨Propiedad no se encuentra en la base de datos.'
            return (text)
        elif sitio == "portal":
            pass
        else:
            if obtainPropFromYapo(link) is not False:
                propiedad = obtainPropFromYapo(link)

    else:
        regYapoDict = {
            "metropolitana": "15",
            "valparaiso": "6",
            "Valparaíso": "6",
            "arica": "1",
            "iquique": "2",
            "antofagasta": "3",
            "atacama": "4",
            "coquimbo": "5",
            "ohiggins": "7",
            "maule": "8",
            "ñuble": "16",
            "biobio": "9",
            "araucania": "10",
            "los Rios": "11",
            "los Lagos": "12",
            "aysen": "13",
            "magallanes": "14",
        }

        propiedad = list(propiedad)

        region = str(propiedad[1])
        regionP = region
        regionY = regYapoDict[region.lower()]
        if region == '15':
            regionP = 'metropolitana'
        if region == 'metropolitana':
            regionY = '15'
        operacion = str(propiedad[2])
        tipo = str(propiedad[3])
        precio = float(propiedad[4])
        dormitorios = str(propiedad[5])
        banos = str(propiedad[6])
        metrosmin = str(propiedad[7])
        metrosmax = str(propiedad[8])
        estacionamientos = str(propiedad[9])
        bodegas = str(propiedad[10])
        lat = str(propiedad[11])
        lon = str(propiedad[12])
        link = str(propiedad[13])
        if sitio == 'portal':
            if operacion == 'venta':
                comuna = str(link.split('/')[5])
                comuna = comuna.replace('-' + str(regionP), '')
                comuna = comuna.replace('-', ' ')
                comuna = comuna.capitalize()
                propiedad.append(comuna)

            else:
                comuna = str(link.split('/')[6])
                comuna = comuna.replace('-metropolitana', '')
                comuna = comuna.replace('-', ' ')
                comuna = comuna.capitalize()
                propiedad.append(comuna)
        else:
            comuna = str(propiedad[14])
    #Revisar si existe aun la publicacion
    if not pubPortalExiste.publicacionExiste(link):
        text = 'Propiedad ya no se encuentra disponible en el sitio.'
        return (text)
    #sacar informacion de la publicacion
    #sacar urls fotos portal
    matrixdescripcion = []
    matrixcounter = 0
    matrixdescripcion.append('')

    if sitio == 'portal':
        first = True
        url = []
        page = requests.get(
            link, headers={'User-Agent': agentCreator.generateAgent()})
        metatext = page.text
        metatext = metatext.split(' ')
        descripcion = []
        savedescripcion = False
        for texto in metatext:

            if 'item-description__text' in texto:
                savedescripcion = True
            if '/div' in texto:
                if savedescripcion:
                    descripcion.append(str(texto))
                savedescripcion = False
            if savedescripcion:
                descripcion.append(str(texto))

        descripcion2 = descripcion.copy()

        first = (descripcion2[0])
        first = first.split(">")
        print(first)
        first = first[2]
        descripcion[0] = first

        last = descripcion2[-1]
        last = last.split("<")
        last = last[0]
        descripcion[-1] = last

        #descripcion=descripcion[2:]
        print(descripcion)
        descripcion = list(descripcion)

        if not interna:
            for desc in descripcion:
                desc = desc.replace('   ', '')
                desc = desc.replace('<br />', ' ')
                desc = desc.replace('<br/>', ' ')
                desc = desc.replace('<br>', ' ')
                desc = desc.replace('<b/>', '')
                desc = desc.replace('<b>', '')
                desc = desc.replace('</b>', '')
                desc = desc.replace('<br', '')
                desc = desc.replace('/>', '')
                desc = desc.replace('&#237;', 'í')
                desc = desc.replace('&#233;', 'é')
                desc = desc.replace('&#243;', 'ó')
                desc = desc.replace('&#225;', 'á')
                desc = desc.replace('&#250;', 'ú')
                desc = desc.replace('&#241;', 'ñ')
                desc = desc.replace('&#209;', 'Ñ')

                if "+56" in desc:
                    desc = "**"
                if len(desc) >= 6:
                    try:
                        desc.replace('\n', "")
                        int(desc)
                        desc = "**"
                    except:
                        pass

                if "@" in desc:
                    desc = "***"

                if ((len(matrixdescripcion[matrixcounter]) + len(desc)) >= 78):

                    matrixcounter += 1
                    matrixdescripcion.append('')
                    if desc != '':
                        matrixdescripcion[matrixcounter] = matrixdescripcion[
                            matrixcounter] + str(desc)
                else:
                    if first:
                        if desc != '':
                            matrixdescripcion[
                                matrixcounter] = matrixdescripcion[
                                    matrixcounter] + str(desc)
                        first = False
                    else:
                        if desc != '':
                            matrixdescripcion[
                                matrixcounter] = matrixdescripcion[
                                    matrixcounter] + ' ' + str(desc)
            print(matrixdescripcion)
            for x, matrix in enumerate(matrixdescripcion):
                matrix = matrix.replace('<br />', '\n')
                matrix = matrix.replace('<br/>', '\n')
                matrix = matrix.replace('<br>', '\n')
                matrix = matrix.replace('<b/>', '')
                matrix = matrix.replace('<b>', '')
                matrix = matrix.replace('</b>', '')
                matrixdescripcion[x] = matrix
            descripcion = '\n'.join(matrixdescripcion)
            propiedad.append(descripcion)

        else:
            descripcion = ' '.join(descripcion)
            descripcion = descripcion.replace('   ', '')
            descripcion = descripcion.replace('<br />', '\n')
            descripcion = descripcion.replace('<br/>', '\n')
            descripcion = descripcion.replace('<br>', '\n')
            descripcion = descripcion.replace('<b/>', '')
            descripcion = descripcion.replace('<b>', '')
            descripcion = descripcion.replace('</b>', '')
            descripcion = descripcion.replace('<br', '')
            descripcion = descripcion.replace('/>', '')
            descripcion = descripcion.replace('&#237;', 'í')
            descripcion = descripcion.replace('&#233;', 'é')
            descripcion = descripcion.replace('&#243;', 'ó')
            descripcion = descripcion.replace('&#225;', 'á')
            descripcion = descripcion.replace('&#250;', 'ú')
            descripcion = descripcion.replace('&#241;', 'ñ')
            descripcion = descripcion.replace('&#209;', 'Ñ')

            propiedad.append(descripcion)
            print(propiedad)

        for meta in metatext:

            if 'data-full-images' in meta:
                meta = meta.split(';')
                for met in meta:
                    if 'mlstatic' in met:
                        met = met.split('&')
                        met = met[0]
                        met = met.replace(".webp", ".jpg")
                        url.append(str(met))

    #Sacar urls fotos yapo
    else:

        url = []
        page = requests.get(
            link, headers={'User-Agent': agentCreator.generateAgent()})
        metatext = page.text
        metatext = metatext.split(' ')
        descripcion = []
        savedescripcion = False
        saveimg = False
        og = True

        for texto in metatext:

            if '<h4>Descripción</h4>' in texto:
                savedescripcion = True

            if og and 'og:image' in texto:
                saveimg = True
                og = False
            if 'img/yapo' in texto:
                saveimg = False
            if savedescripcion:
                descripcion.append(str(texto))
            if '</div>' in texto:
                savedescripcion = False
            if saveimg and 'img.yapo.cl/images' in texto:
                texto = texto.replace('content="', '')
                texto.replace('"', '')
                url.append(texto)
            if 'phone-url' in texto:
                texto = texto.split('"')
                texto = texto[1]
                auxPhone = texto
                auxPhone = 'https://www.yapo.cl' + auxPhone
        descripcion = descripcion[1:]
        first = True
        print(descripcion)
        for desc in descripcion:
            desc = desc.replace('\n', ' ')
            desc = desc.replace('<br />', '\n')
            desc = desc.replace('</div>', '\n')
            desc = desc.replace('<br>', '\n')
            desc = desc.replace('<br', '')
            desc = desc.replace('/>', '')
            desc = desc.replace('itemprop="description">', "")
            desc = desc.replace('</p>', '\n')
            desc = desc.replace("\t", "")
            desc = desc.replace('<!', '')
            desc = desc.replace('--', '')
            desc = desc.replace('  ', '')
            desc = desc.replace('\n', ' ')

            if ((len(matrixdescripcion[matrixcounter]) + len(desc)) >= 78):

                matrixcounter += 1
                matrixdescripcion.append('')
                matrixdescripcion[matrixcounter] = matrixdescripcion[
                    matrixcounter] + str(desc)
            else:
                if first:
                    matrixdescripcion[matrixcounter] = matrixdescripcion[
                        matrixcounter] + str(desc)
                    first = False
                else:
                    matrixdescripcion[matrixcounter] = matrixdescripcion[
                        matrixcounter] + ' ' + str(desc)

        print(matrixdescripcion)
        descripcion = '\n'.join(matrixdescripcion)

        propiedad.append(descripcion)

        try:
            print(auxPhone)
            response = requests.get(
                auxPhone, headers={'User-Agent': agentCreator.generateAgent()})
            auxphone2 = auxPhone
            img = Image.open(BytesIO(response.content))
            img = img.convert('L')
            img = img.convert('1')
            img.save("auxphone.gif")
            auxPhone = 1
        except:
            pass
    lenfotos = len(url)

    if len(url) == 0:
        print("la propiedad no cuenta con fotografias")
    else:
        print('total fotos: ' + str(len(url)))
        for x, u in enumerate(url):
            u = u.replace('"', '')
            response = requests.get(u)
            img = Image.open(BytesIO(response.content))
            img.save(str(x) + " foto.jpg")

    if not interna:
        imagenDescripcion = Image.new('RGB', (456, 345), color=(255, 255, 255))

        d = ImageDraw.Draw(imagenDescripcion)
        f = ImageFont.truetype('arial.ttf', 12)
        d.text((0, 0), descripcion, font=f, fill=(0, 0, 0))

        imagenDescripcion.save('imagenDescripcion.png')

    datospro = []
    if pro:

        propsPV = reportes.from_portalinmobiliario(tipo, regionP, [comuna],
                                                   "venta", True)
        propsYV = reportes.from_yapo(tipo, regionY, [comuna], True, "venta",
                                     True)
        propsV = propsPV + propsYV
        # aca deberiamos hacer el GB

        m2 = reportes.m2prom(tipo, comuna, region)
        m2V = m2[0]
        m2A = m2[1]

        clfHV = ensemble.GradientBoostingRegressor(n_estimators=400,
                                                   max_depth=5,
                                                   min_samples_split=2,
                                                   learning_rate=0.1,
                                                   loss='huber')

        #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link

        preciosV = [row[5] for row in propsV]

        trainingV = propsV.copy()
        for row in trainingV:
            del row[13]
            if tipo not in ["departamento", "Casa", "Oficina"]:
                del row[12]
                del row[7]
                if tipo != "local":
                    del row[6]
            del row[5]
            del row[4]
            del row[3]
            del row[2]
            del row[1]
            del row[0]

        x_train, x_test, y_train, y_test = train_test_split(trainingV,
                                                            preciosV,
                                                            test_size=0.10,
                                                            random_state=2)

        #obtain scores venta:
        clfHV.fit(x_train, y_train)
        print("-----------")
        print("Score Huber:")
        print(clfHV.score(x_test, y_test))
        scoreV = clfHV.score(x_test, y_test)

        clfHV.fit(trainingV, preciosV)

        propsPA = reportes.from_portalinmobiliario(tipo, regionP, [comuna],
                                                   "arriendo", True)
        propsYA = reportes.from_yapo(tipo, region, [comuna], True, "arriendo",
                                     True)
        propsA = propsPA + propsYA
        # aca deberiamos hacer el GB

        clfHA = ensemble.GradientBoostingRegressor(n_estimators=400,
                                                   max_depth=5,
                                                   min_samples_split=2,
                                                   learning_rate=0.1,
                                                   loss='huber')

        #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link

        preciosA = [row[5] for row in propsA]

        trainingA = propsA.copy()
        for row in trainingA:
            del row[13]
            if tipo not in ["departamento", "Casa", "Oficina"]:
                del row[12]
                del row[7]
                if tipo != "local":
                    del row[6]
            del row[5]
            del row[4]
            del row[3]
            del row[2]
            del row[1]
            del row[0]

        x_train, x_test, y_train, y_test = train_test_split(trainingA,
                                                            preciosA,
                                                            test_size=0.10,
                                                            random_state=2)

        #obtain scores arriendo:
        clfHA.fit(x_train, y_train)
        print("-----------")
        print("Score Huber:")
        print(clfHA.score(x_test, y_test))
        scoreA = clfHA.score(x_test, y_test)

        clfHA.fit(trainingA, preciosA)

        textmail += "Resultados comuna " + str(
            comuna) + ":\n" + "Score Ventas: " + str(
                (int(10000 * scoreV)) / 100) + "%\nScore Arriendos: " + str(
                    (int(10000 * scoreA)) /
                    100) + "%\nPrecio m2 Venta: UF." + str(
                        (int(10 * (m2V / ufn))) /
                        10) + "\nPrecio m2 Arriendo: $" + str(
                            (int(m2A))) + "\n\n"

        if tipo not in ["departamento", "Casa", "Oficina"]:
            prop = [banos, metrosmin, metrosmax, lat, lon]
            if tipo != "local":
                prop = [metrosmin, metrosmax, lat, lon]
        else:
            prop = [
                dormitorios, banos, metrosmin, metrosmax, lat, lon,
                estacionamientos
            ]

        tasacionVenta = clfHV.predict([prop])
        tasacionArriendo = clfHA.predict([prop])

        precioV = tasacionVenta
        precioA = tasacionArriendo
        print("el precio tasado de venta inicial es: " + str(precioV))
        print("el precio tasado de arriendo inicial es: " + str(precioA))

        if operacion == 'venta':

            if precioV is None or precioV < 0.1:
                pro = False
                financiera = False

            try:
                rentaV = ((precioV - precio) / precio)
            except:
                pro = False
                financiera = False
                text2 = 'No se ha podido realizar tasación'
                print('fail 1')

            if precioA is None or precioA < 0.01:
                pro = False
                financiera = False

            try:
                rentaA = (precioA * 12 / precio)

            except:
                pro = False
                financiera = False
                text2 = 'No se ha podido realizar tasación'
                print('fail 2')

            if pro:
                if rentaA > 0.2:
                    pro = False
                    financiera = False
                    print('fail 3')

                if rentaA < 0:
                    pro = False
                    financiera = False

            if pro:
                # precio venta tasado
                datospro.append(precioV)
                # rentabilidad de venta
                datospro.append(float(rentaV))

                # precio arriendo tasado
                datospro.append(precioA)
                # rentabilidad de arriendo
                datospro.append(float(rentaA))

        else:

            try:
                precioA = tasacionArriendo

            except:
                pro = False
                text2 = 'No se ha podido realizar tasación'
                print('fail 72')

            if pro:
                if precioA is None or precioA < 0.01:
                    pro = False
                    text2 = 'No se ha podido realizar tasación'
                    print('fail 8')

            if pro:
                # precio arriendo tasado
                datospro.append(precioA)
                # rentabilidad de arriendo

    datoscontacto = []
    if interna:

        if sitio == 'portal':
            try:
                email, telefono, dueno = reportes.getDatosDueno(str(id))
            except:
                email = "NN"
                telefono = "NN"
                dueno = "NN"

        else:
            email = "NN"
            if auxPhone == 1:
                telefono = auxphone2
            else:
                telefono = "NN"
            dueno = 'NN'
        datoscontacto.append(email)
        datoscontacto.append(telefono)
        datoscontacto.append(dueno)

    #Crear PDF
    if interna:
        nombrearchivo = "Ficha Propiedad Sitio:" + str(sitio) + " Id:" + str(
            id) + ".pdf"
    else:
        nombrearchivo = "Ficha Propiedad Sitio:" + str(sitio) + ", " + str(
            operacion) + ", " + str(tipo) + ", " + str(region) + ", " + str(
                comuna) + ".pdf"

    print(nombrearchivo)
    links = []
    if financiera:
        pro = "financiera"
    print("entering pdfCreator")
    pdfCreatorFichas.crearPdfFicha(nombrearchivo, id, propiedad, lenfotos, pro,
                                   datospro, interna, datoscontacto, regionP,
                                   links)
    print("pdf generado con exito")
    #Enviar PDF
    sendmail.sendMail(mail, "", nombrearchivo)

    #Eliminar del servidor

    if len(url) == 0:
        pass
    else:
        for x, u in enumerate(url):
            os.remove(str(x) + " foto.jpg")
    try:
        os.remove("auxphone.gif")
    except:
        pass

    if not interna:
        try:
            os.remove("imagenDescripcion.png")
        except:
            pass
    os.remove(nombrearchivo)

    #Retornar exito
    text = "Ficha creada para la propiedad: " + str(
        id) + " obtenida del sitio: " + str(
            sitio) + ", enviada con éxito al correo: " + str(mail) + "."
    if text2 != '':
        text = text2 + '. ' + text
    return (text)