[R-SIG-Finance] [R] hist from a list

Pedro páramo percent||101 @end|ng |rom gm@||@com
Tue Aug 4 22:27:51 CEST 2020


Many thanks Rui,

Base R graphic is working on R, on my pc. the other one, no working but the
output on first its perfect.
The question I answer asking you again (and giving again many thanks for
the help) is because I am trying to run "my code" also on a web, and it is
telling me "error in External(c_X11...unable to start device X11cairo
execution halted.

It seems X11 starts a window and because of linux it doesn´t work.

There is a way to plot a bar plot more basic without starting X11?  A most
simple barplot?

I am trying but no way for the moment, I will attach if I get it.

> str(bwch)
'data.frame': 35 obs. of  2 variables:
 $ Accion: Factor w/ 35 levels "Acciona","Acerinox",..: 20 31 26 30 32 27
10 6 34 3 ...
 $ reval : num  -0.728 -0.695 -0.61 -0.491 -0.478 ...

and if I show bwch it shows me:

bwch
          Accion       reval
20           IAG -0.72840710
7       Sabadell -0.69537488
22         Melia -0.61043257
26        Repsol -0.49057941
8      Santander -0.47802975
23        Merlin -0.44619155
6           BBVA -0.42222597
4        Amadeus -0.40382211
28    Telefonica -0.39731736
2            ACS -0.38902365
5  ArcelorMittal -0.38367478
35         Indra -0.35756385
34      Almirall -0.35348361
19      Colonial -0.34791954
13          ENCE -0.32316076
32           CIE -0.32168004
21        Mapfre -0.29317220
9      Bankinter -0.29175725
10     CaixaBank -0.29116305
3           Aena -0.29101729
18       Inditex -0.28585061
31        Bankia -0.26246599
24       Naturgy -0.25511571
30      Acerinox -0.22028220
15     Ferrovial -0.20837519
16       Grifols -0.20712695
12        Enagas -0.04890202
25           REE -0.02601443
1        Acciona  0.02695608
14        Endesa  0.06325043
33      MasMovil  0.11111111
17     Iberdrola  0.25801888
27       SGamesa  0.31594178
29      Viscofan  0.33694859
11       Cellnex  0.38261067

Could in some way to "save" bwch data as a plain matrix and "read" it from
zero and then could plot a barplot without x11?
Many thanks again for your help




El lun., 3 ago. 2020 a las 23:45, Rui Barradas (<ruipbarradas using sapo.pt>)
escribió:

> Hello,
>
> Thanks for the data in dput format.
> If you run
>
> str(bwchist)
>
> you will see that what you have is a data.frame, yes, but, with columns of
> class "list", not vectors.
> So the first step is to make them vectors, to unlist the lists. I will do
> it applying function unlist() to each of the columns. Since lapply returns
> a list, I remake a data.frame. The original is kept unchanged, the new
> object is bwch.
>
> bwch <- lapply(bwchist, unlist, recursive = FALSE)
> bwch <- do.call(cbind.data.frame, bwch)
> str(bwch)
>
>
> Now that everything is as it should, here are two ways of plotting bar
> graphs.
>
> #--- base R
> x11(width = 11.5, height = 6)
> old_par <- par(mar =  par("mar") + c(1, 0, 0, 0))
> bp <- barplot(bwch$reval, yaxt = "n", ylim = c(-1, 0.4))
> axis(1, at = bp, labels = bwch$Accion, las = 2)
> axis(2, at = pretty(bwch$reval))
> par(old_par)
>
>
> #--- package ggplot2
> library(ggplot2)
>
> x11(width = 11.5, height = 6)
> ggplot(bwch, aes(factor(Accion, levels = Accion), reval)) +
>   geom_col() +
>   theme(axis.text.x = element_text(angle = 60, hjust = 1))
>
>
> Hope this helps,
>
> Rui Barradas
>
> Às 19:48 de 03/08/2020, Pedro páramo escreveu:
>
> Hi Rasmus, Josh and Rui,
>
> First of all many thanks in advance about your help.
>
> The first thig is sometimes you say " you are posting in HTML and that
> makes the
> post unreadable as this is a plain text list" how can I put the code in
> the correct way, not html (attaching in txt?)
>
> The second about the code:
>
> I have used this:
>
> bwc <- cbind(bwfinal2,bwfinal)
> colnames(bwc)=c("Accion","reval")
> df <- matrix(unlist(bwc), nrow=nrow(bwc), byrow=F)
> colnames(bwchist)=c("Accion","reval")
> bwchist <-as.data.frame(bwc[order(df[,2]), ])
>
> bwchist is the ordered cum stock returns in the year but because is a list
> it is not possible to plot and histogram with x (names of stocks) and the x
> axist the value of cum stocks (reval)
>
> when I put dput(bwchist) the console says:
>
> dput(bwchist)
> structure(list(Accion = list("REE", "Enagas", "Grifols", "Ferrovial",
>     "Acerinox", "Naturgy", "Inditex", "Bankia", "ENCE", "Aena",
>     "Bankinter", "Mapfre", "CaixaBank", "CIE", "Colonial", "Almirall",
>     "Indra", "ArcelorMittal", "ACS", "Telefonica", "Amadeus",
>     "BBVA", "Merlin", "Santander", "Repsol", "Melia", "Sabadell",
>     "IAG", "Acciona", "Endesa", "MasMovil", "Iberdrola", "SGamesa",
>     "Viscofan", "Cellnex"), reval = list(-0.0200827282700085,
>     -0.0590294115600855, -0.214126598790964, -0.220773677809979,
>     -0.229653300324357, -0.257944379583984, -0.283942789063822,
>     -0.285159347392533, -0.303814713896458, -0.30734460425763,
>     -0.309408155539818, -0.319912221435868, -0.322790949659181,
>     -0.344047579452905, -0.347919538415482, -0.356898907103825,
>     -0.374263261296661, -0.40147247119078, -0.405150043834815,
>     -0.406022775042175, -0.413786100987797, -0.440679109311707,
>     -0.442603156492871, -0.491634140733524, -0.499254932434042,
>     -0.6, -0.709737357505148, -0.724461258850966, 0.0220528711420083,
>     0.0462767672643172, 0.115044247787611, 0.238734548714937,
>     0.274578114644054, 0.343422896082666, 0.387826126094928)), class =
> "data.frame", row.names = c(NA,
> -35L))
>
> I try to make an hist or barplot but because it is a list no way to obtain
> the plot.
>
> Many thanks again for your help.
>
> I have printed two manuals to improve my level, but if you can help me, I
> would be very very gratefull.
>
>
>
> El vie., 31 jul. 2020 a las 18:28, Rasmus Liland (<jral using posteo.no>)
> escribió:
>
>> On 2020-07-31 10:07 -0500, Joshua Ulrich wrote:
>> | On Fri, Jul 31, 2020 at 9:55 AM Rui Barradas wrote:
>> | | Às 15:44 de 31/07/2020, Michael Dewey escreveu:
>> | | | Dear Pedro
>> | | |
>> | | | Some comments in-line
>> | | |
>> | | | On 30/07/2020 21:16, Pedro páramo wrote:
>> | | | | Hi all,
>> | | | |
>> | | | | I attach my code, the think is I
>> | | | | want to make a bar plot the last
>> | | | | variable called "bwchist" so the
>> | | | | X axis are "Accion" and the y
>> | | | | axis are "reval" values.
>> | | | |
>> | | | | I have prove class(bwchist) and
>> | | | | says dataframe but its still a
>> | | | | list because it says me I have
>> | | | | prove to unlist, but it doesnt
>> | | | | work
>> | | | |
>> | | | | hist(bwchist)
>> | | | | Error in hist.default(bwchist) : 'x' must be numeric
>> | | |
>> | | | So bwchist is not a numeric
>> | | | variable as hist needs. Aboce you
>> | | | said it is a data frame but data
>> | | | frames are not numeric.
>> | | |
>> | | | For future reference your example
>> | | | is way too long for anyone to go
>> | | | through and try to help you. Try
>> | | | next time to reduce it to the
>> | | | absolute minimum by removing
>> | | | sections while you still get the
>> | | | error.  It is also easier to get
>> | | | help if you can remove unnecessary
>> | | | packages.
>> | | |
>> | | | It is also unreadable because you
>> | | | are posting in HTML and that makes
>> | | | the post unreadable as this is a
>> | | | plain text list.
>> | |
>> | | Hello,
>> | |
>> | | I second Michael's opinion. When the
>> | | post's code is very long, there is a
>> | | tendency to have less answers.
>> | |
>> | | Please post the output of
>> | |
>> | |     dput(head(bwchist, 30))
>> | |
>> | | It's much shorter code and it
>> | | recreates the data so we will be
>> | | able to see what's wrong and try to
>> | | find a solution.
>> |
>> | Hi Pedro,
>> |
>> | Another 'best practice' and polite
>> | thing to do is link to other places
>> | you may have cross-posted.  That will
>> | give people the opportunity to see if
>> | your questions has been answered in
>> | another forum.
>> |
>> | I saw your post on R-SIG-Finance
>> | (https://stat.ethz.ch/pipermail/r-sig-finance/2020q3/014979.html),
>> | and started to work on a solution.
>> |
>> | I don't know how to do this in
>> | tidyquant, but here's how you can do
>> | it with quantmod:
>> |
>> | # all tickers
>> | tk <- c("ANA.MC", "ACS.MC", "AENA.MC", "AMS.MC", "MTS.MC", "BBVA.MC", "
>> SAB.MC",
>> |   "SAN.MC", "BKT.MC", "CABK.MC", "CLNX.MC", "ENG.MC", "ENC.MC", "ELE.MC
>> ",
>> |   "FER.MC", "GRF.MC", "IBE.MC", "ITX.MC", "COL.MC", "IAG.MC", "MAP.MC",
>> |   "MEL.MC", "MRL.MC", "NTGY.MC", "REE.MC", "REP.MC", "SGRE.MC", "TEF.MC
>> ",
>> |   "VIS.MC", "ACX.MC", "BKIA.MC", "CIE.MC", "MAS.MC", "ALM.MC", "IDR.MC
>> ")
>> |
>> | # download them into an environment ('e')
>> | require(quantmod)
>> | getSymbols(tk, from = "2019-12-31", env = (e <- new.env()))
>> |
>> | # extract adjusted close column
>> | adj <- lapply(e, Ad)
>> | # calculate daily returns from adjusted data,
>> | # merge into a xts matrix, and fill NA with 0
>> | ret <- do.call(merge, c(lapply(adj, dailyReturn), fill = 0))
>> | # cumulative returns
>> | cumret <- cumprod(1 + ret) - 1
>> | # set names
>> | colnames(cumret) <- names(adj)
>> | last(cumret)
>> | # calculate histogram for period-to-date returns
>> | hist(drop(last(cumret)))
>> |
>> | I'm not sure that's the histogram
>> | you're looking for, but I hope it
>> | gives you a start toward a solution.
>> |
>> | Best,
>> | Josh
>>
>> Wow Josh!  That's very elegant.
>>
>> Myself now, I just plowed through the
>> original code to make it simpler, but am
>> at a loss as to how this histogram looks
>> ...
>>
>>         x <- c("ANA.MC", "ACS.MC", "AENA.MC", "AMS.MC", "MTS.MC", "
>> BBVA.MC",
>>           "SAB.MC", "SAN.MC", "BKT.MC", "CABK.MC", "CLNX.MC", "ENG.MC",
>>           "ENC.MC", "ELE.MC", "FER.MC", "GRF.MC", "IBE.MC", "ITX.MC",
>>           "COL.MC", "IAG.MC", "MAP.MC", "MEL.MC", "MRL.MC", "NTGY.MC",
>>           "REE.MC", "REP.MC", "SGRE.MC", "TEF.MC", "VIS.MC", "ACX.MC",
>>           "BKIA.MC", "CIE.MC", "MAS.MC", "ALM.MC", "IDR.MC")
>>         stock.prices <-
>>           lapply(x, function(stock) {
>>             tidyquant::tq_get(x=stock,from = '2019-12-31',get =
>> "stock.prices")
>>           })
>>         names(stock.prices) <- x
>>
>>         library(tidyquant)
>>
>>         returns <- lapply(stock.prices, function(data) {
>>           tab <-
>>             tq_transmute(
>>               data = data,
>>               select = adjusted,           # this specifies which column
>> to select
>>               mutate_fun = periodReturn,   # This specifies what to do
>> with that column
>>               period = "daily",            # This argument calculates
>> Daily returns
>>               col_rename = "idr_returns")  # renames the column
>>           tab[,"cr"] <- cumprod(1 + tab[,"idr_returns"])
>>           tab[,"cumulative_returns"] <- tab[,"cr"] - 1
>>
>>           dplyr::pull(
>>             tab[nrow(tab[,"cumulative_returns"]),
>>                           "cumulative_returns"]
>>           )
>>         })
>>
>>         bestworst <- simplify2array(returns)
>>
>>         namebw <-
>>           c("Acciona", "ACS", "Aena", "Amadeus",
>>             "ArcelorMittal", "BBVA", "Sabadell",
>>             "Santander", "Bankinter",
>>             "CaixaBank", "Cellnex", "Enagas",
>>             "ENCE", "Endesa", "Ferrovial",
>>             "Grifols", "Iberdrola", "Inditex",
>>             "Colonial", "IAG", "Mapfre",
>>             "Melia", "Merlin", "Naturgy", "REE",
>>             "Repsol", "SGamesa", "Telefonica",
>>             "Viscofan", "Acerinox", "Bankia",
>>             "CIE", "MasMovil", "Almirall",
>>             "Indra")
>>
>>         bwc <- data.frame(
>>           symbol=names(bestworst),
>>           Accion=namebw,
>>           reval=bestworst)
>>
>> | | | | bwc<-cbind(bwfinal2,bwfinal)
>> | | | | colnames(bwc)=c("Accion","reval")
>> | | | | bwc <- as.data.frame(bwc)
>>
>> ... aaaand you know something's
>> happening between here (where bwchist is
>> created), but you don't know what it is,
>> do you, Mr páramo?
>>
>> | | | | colnames(bwchist)=c("Accion","reval")
>> | | | | bwchist <-as.data.frame(bwc[order(bwc$reval), ])
>>
>> Best,
>> Rasmus
>>
>
>
>
> <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient> Sem
> vírus. www.avast.com
> <https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient>
> <#m_-3158995779444775478_DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
>

	[[alternative HTML version deleted]]



More information about the R-SIG-Finance mailing list