miércoles, 22 de enero de 2020

Ley D'hont

Nescanos <- 57
PorMin <- 0.05
df <- data.frame( Carmena = .284, PP = .219, Ciudantans = .218, PSOE = .137, Franco = .082, IU = 0.023, Total = 1642898)
df <- df[ , df >= PorMin ]
df <- df[ , order(df, decreasing = TRUE)]
df <- df$Total * df
df$PP <- df$PP + 3105
# EscañoPara
# Carmena Ciudantans     Franco         PP       PSOE
#      18         13          5         13          8

df$Total <- rm()
EscanosDF <- df
for( i in 2:Nescanos ){
  EscanosDF <- rbind( EscanosDF , df/i)
}


EscañoPara <-  c()

i <- 1 +1
for( i in 1:Nescanos){
  cat("repartiendo escaño ", i, "\n")
  print( sapply(X = EscanosDF, FUN = max, na.rm = TRUE) )
  print( sapply(X = EscanosDF, FUN = function(x){  max(  length( x [ is.na(x) == TRUE]  )  ) + 1  }) )
  Maximo <- max( EscanosDF , na.rm = TRUE)[1]
  Fila <- which( apply(X = EscanosDF, MARGIN = 1, FUN = function(x){  any(x == Maximo)}) )
  Fila <- Fila[ length(Fila)]
  Columna <- which.max( EscanosDF[Fila,  ] )[1]
  nombrePartido <- names(Columna)
  EscanosDF[ Fila, Columna] <- NA
  EscañoPara <- c(EscañoPara, nombrePartido )
  cat("Escaño Para", nombrePartido, "\n")

}

table( EscañoPara)
EscañoPara

Paseando por shiny dygraph y R Markdown

Dy grpah es una de las librearias más diveridas vamos a ver como generar grupo de gráficos, tablas y grafico interactivos con markdown y shiny


---
title: "Pruebas Shiny"
author: "jvigo6n"
date: "21 de enero de 2020"
output: html_document
  # ioslides_presentation:
  #   keep_md: yes
  #   widescreen: yes
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

# La bolse y R (Paquete quantMode) {.tabset }
Vamos a hacer un mardown para tradear, para ver los nombres de las compañias aquí [YahooFinanciero](https://finance.yahoo.com/quote/TEF?p=TEF&.tsrc=fin-srch  ).

## Genera Grupos de dygraph {.tabset }
```{r dygraphs sincro , echo=FALSE, error=FALSE, warning= FALSE, message=FALSE}
# https://finance.yahoo.com/quote/TEF?p=TEF&.tsrc=fin-srch
library(dplyr)
library(dygraphs)
library(DT)
library(quantmod)

tickers <- c("AAPL", "MSFT", "IBM", "TEF")
getSymbols(tickers)
closePrices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))
dateWindow <- c("2008-01-01", "2009-01-01")

dygraph(closePrices, main = "Value", group = "stock") %>%
  dyRebase(value = 100) %>%
  dyRangeSelector(dateWindow = dateWindow)

dygraph(closePrices, main = "Percent", group = "stock") %>%
  dyRebase(percent = TRUE) %>%
  dyRangeSelector(dateWindow = dateWindow)

dygraph(closePrices, main = "None", group = "stock2") %>%
  dyRangeSelector(dateWindow = dateWindow)


```

## Interactive Table {.tabset }
```{r dygraphs}
# https://shiny.rstudio.com/gallery/basic-datatable.html
closePrices2 <- closePrices %>% data.frame()
closePrices2$Fecha <- index(closePrices)
closePrices2 <-
  closePrices2[ , c("Fecha", names(closePrices2) [ names(closePrices2) != "Fecha"] )]
row.names(closePrices2) <- rm()
# closePrices2

shinyApp(
  ui = fluidPage(
    selectInput("compania", "Companyia:",
                c("APPLE" = "AAPL.Close",
                  "Microsft" = "MSFT.Close",
                  "IBM" = "IBM.Close",
                  "Telefonica" = "TEF.Close"), state.name, multiple= T, selectize=T) 
    , tableOutput("data")
    , dataTableOutput("DT")
  ),
  server = function(input, output) {
    output$data <-  renderTable({
      if( length(input$compania)> 0 ){
        x <- closePrices2[ ,   c("Fecha" ,names(closePrices2)[ names(closePrices2) %in% 
                                                         input$compania
                                                          # "TEF.Close"
                                                         ] ) ]
        x <- x[order(x[,2], decreasing = TRUE),][1:10,]
        x$Fecha  <- x$Fecha %>%  as.Date %>% as.character()
        x
      }else{
        closePrices2[ !1:nrow(closePrices2),]
      }
      }, rownames = FALSE)
    output$DT <-  renderDataTable({
      if( length(input$compania)> 0 ){
        x <- closePrices2[ ,  names(closePrices2) %in% c("Fecha", input$compania)]
        x <- x[order(x[,1], decreasing = TRUE),]
        x
      }else{
        x <- closePrices2
        x <- x[ !1:nrow(closePrices2),]
        x
      }})
        
  })
```

## Shiny {.tabset }
```{r Shiny}
closePrices3 <- closePrices
# closePrices2

plotdyg <- function(dataPlot){
  dygraph(dataPlot, main = "None", group = "stock") %>%
  dyRangeSelector(dateWindow = dateWindow)
}

shinyApp(
  ui =  fluidPage(
    selectInput("compania", "Companyia:",
                c("APPLE" = "AAPL.Close",
                  "Microsft" = "MSFT.Close",
                  "IBM" = "IBM.Close",
                  "Telefonica" = "TEF.Close"), state.name, multiple= T, selectize=T)
    , dygraphOutput("dyg")
    , dygraphOutput("dyg2")
    # , dataTableOutput("DT")
  ),
  server = function(input, output) {
    output$dyg <-  renderDygraph({
      if( length(input$compania)> 0 ){
        x <- closePrices3[ , names(closePrices3) %in% input$compania ]
        plotdyg( x )
      }else{
        plotdyg( closePrices3[ !1:nrow(closePrices2),] )
      }
      })
    output$dyg2 <-  renderDygraph({plotdyg( closePrices3 )})
  })
```


## Interactive Plot {.tabset }
```{r dygraphs2}
# https://shiny.rstudio.com/gallery/basic-datatable.html
closePrices4 <- closePrices
# closePrices2

plotdyg <- function(dataPlot){
  dygraph(dataPlot, main = "None", group = "stock") %>%
  dyRangeSelector(dateWindow = dateWindow)
}

selectInput(inputId = "compania", label = "Companyia:",
            choices = c("APPLE" = "AAPL.Close",
                        "Microsft" = "MSFT.Close",
                        "IBM" = "IBM.Close",
                        "Telefonica" = "TEF.Close"), state.name, multiple= T, selectize=T) 

renderDygraph({
  if( length(input$compania)> 0 ){
    x <- closePrices3[ , names(closePrices3) %in% input$compania ] 
    plotdyg( x )
    }else{
      plotdyg( closePrices3[ !1:nrow(closePrices2),] )
      }
  })
renderDygraph({plotdyg( closePrices3 )})  


sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30)

renderPlot({
  x <- faithful[, 2]  # Old Faithful Geyser data
  bins <- seq(min(x), max(x), length.out = input$bins + 1)

  # draw the histogram with the specified number of bins
  hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
```