Как сделать коэффициенты со звёздочками уровня значимости в LaTeX’е

In this quick entry, it will be shown how it is possible to format regression output tables in LaTeX and automatically print significance codes (in the form of stars) without any symbols placed a priori.

First of all, one should obtain estimates and standard errors from any statistical package (preferably R, but as long as homicide is considered a crime punishable by incarceration or death, and using SPSS is not, one can use whatever they want—although the author wishes it were the other way about).

Second, one should use regular expressions or any other dark wizardry in order to convert such table into a list of LaTeX control sequences taking two argument each, possible delimited by an ampersand. Here is an example how this can be done by taking raw Excel output (tab-delimited) and running any regex engine on it.


market	0.0552	0.0055	0.00988	0.00149
ret	-1.974	0.0329	-0.767	0.00993
sls	-1.31	0.36	-0.342	0.128
age	-0.0109	0.0246	-0.00381	0.00663
roa	-0.107	0.107	-0.0733	0.0281
Intercept	-0.586	0.138	-0.165	0.036

Latex table before regular expressions

Regular expression:

s/([A-Za-z]+)\t([-0-9.]+)\t([0-9.]+)\t([-0-9.]+)\t([0-9.]+)/\1 & \\coef{\2}{\3} & \\coef{\4}{\5} \\\\/g


market & \coef{0.0552}{0.0055} & \coef{0.00988}{0.00149} \\
ret & \coef{-1.974}{0.0329} & \coef{-0.767}{0.00993} \\
sls & \coef{-1.31}{0.36} & \coef{-0.342}{0.128} \\
age & \coef{-0.0109}{0.0246} & \coef{-0.00381}{0.00663} \\
roa & \coef{-0.107}{0.107} & \coef{-0.0733}{0.0281} \\
Intercept & \coef{-0.586}{0.138} & \coef{-0.165}{0.036} \\

Latex table after regular expressions

Do not be surprised that now there 3 columns, not 5. Suppose one would like to have the standard error placed beneath the coefficient. Then what?

This is the standard preamble.

\documentclass[11pt, a4paper]{article}

Now, it is time to write a command that would typeset a fixed-width box (because all entries in a column have the same width). The basic building block will have 3 arguments: width (optional), estimate (numeric), and standard error (numeric).


Now, the stars. fp package provides facilities to work with fixed-point arithmetic, which is more than enough in our case. Three significance levels—10%, 5%, and 1%—and normal distribution quantiles will be used because this was initially written for applied people in accounting. For asymptotically normal estimators, the critical values can be obtained via the R command qnorm(), e. g. qnorm(1-0.001/2), which should give 3.29 as the critical value for a two-sided t test of significance at 0.1% level.

\FPset\critsss{2.575829}% 0.995 quantile of the standard normal distribution
\FPset\critss{1.959964}% 0.975 quantile of the standard normal distribution
\FPset\crits{1.644854}% 0.95 quantile of the standard normal distribution
\FPset\coefest{#2}% The first argument is the estimate
\FPset\coefse{#3}% The second argument is the standard error
\FPdiv\zstat{\coefest}{\coefse}% This is the observed t-statistic
\FPabs\zabs{\zstat}% This is its absolute value
\FPiflt\zabs{\crits}\def\kostyrkastar{\relax}\else% Minimising the risk of overwriting an existing command

Since hard def’s are used for brevity, in order to minimise the chance that the star-drawing command overwrites any existing one, one should consider using their family name or the name of their pet as a command prefix—above is an example of precautiousness rather than hubris.

LaTeX output table coefficient significance stars based on the t statistic

Look how stars appear when the absolute value of the $t$ statistic increases.
$\beta_0$ \coef{0.00}{1.0} ($t=0$) \par
$\beta_1$ \coef{1.10}{2.2} ($t=0.5$) \par
$\beta_2$ \coef{2.00}{2.0} ($t=1$) \par
$\beta_3$ \coef{-3.00}{2.0} ($t=-1.5$) \par
$\beta_4$ \coef{5.10}{3.0} ($t=1.7$) \par
$\beta_5$ \coef{-3.80}{2.0} ($t = -1.9$) \par
$\beta_6$ \coef{4.92}{2.5} ($t = 1.968$) \par
$\beta_8$ \coef{19.60}{7.0} ($t = 2.8$) \par
$\beta_9$ \coef{-800}{8.0} ($t = -100$)

LaTeX output table coefficient significance stars in two columns

		& \null\hfill NCSKEW\hfill\null &\null\hfill DUVOL\hfill\null \\
		Market value & \coef{0.0552}{0.0055} & \coef{0.00988}{0.00149} \\
		Return & \coef{-1.974}{0.0329} & \coef{-0.767}{0.00993} \\
		Sales  & \coef{-1.310}{0.36} & \coef{-0.342}{0.128} \\
		Age & \coef{-0.0109}{0.0246} & \coef{-0.00381}{0.00663} \\
		ROA & \coef{-0.107}{0.107} & \coef{-0.0733}{0.0281} \\
		(Constant) & \coef{-0.586}{0.138} & \coef{-0.165}{0.036} \\
		Sector dummies &\null\hfill Yes\hfill\null &\null\hfill Yes\hfill\null \\
		Year dummies &\null\hfill Yes\hfill\null &\null\hfill Yes\hfill\null \\
		Observations &\null\hfill 14\,689\hfill\null &\null\hfill 14\,694\hfill\null \\
		\multicolumn{3}{l}{\footnotesize Significance codes: * $p<0.10$, ** $p<0.05$, *** $p<0.01$.} \\[-.5ex]
		\multicolumn{3}{l}{\footnotesize Cluster-robust (by country) standard errors in brackets.} \\
\caption{OLS estimates}

If one is working in particle physics and needs to use sigma levels, one can be more creative with their notation. For example, one might need more markers or vertcial placement. This can be achieved in an instant.


LaTeX output table coefficient significance stars and standard errors underneath

		& \null\hfill LHC\hfill\null & \null\hfill Sein\hfill\null & \null\hfill Pectus\hfill\null & \null\hfill Corps-nichons \hfill\null\\
		Experiment 1 & \coefnuclear{4.9908}{1.3099} & \coefnuclear{7.4037}{1.2957} & \coefnuclear{5.6249}{1.3124} & \coefnuclear{1.2275}{1.2893} \\[2ex]
		Experiment 2 & \coefnuclear{4.3236}{1.2972} & \coefnuclear{10.0386}{1.3176} & \coefnuclear{3.7301}{1.3056} & \coefnuclear{6.7275}{1.2844} \\[2ex]
		Experiment 3 & \coefnuclear{6.1690}{1.2955} & \coefnuclear{7.9955}{1.2917} & \coefnuclear{1.8410}{1.2883} & \coefnuclear{8.7442}{1.3116} \\[2ex]
		Experiment 4 & \coefnuclear{0.6228}{1.3083} & \coefnuclear{3.0899}{1.2977} & \coefnuclear{9.3049}{1.3027} & \coefnuclear{2.4693}{1.2962} \\
		\multicolumn{3}{l}{\footnotesize Significance codes: ${}^* = 1\sigma$, ${}^. = 0.5\sigma$.} \\
	\caption{Trying to uncover Higgs' bosom}

One can change the placement of \hfill and \null to change the alignment. It is, however, a very delicate matter, and good alignment differs from table to table since sometimes, the decimal separator should serve as the pivot. A good (but rather restrictive in real world) idea would be using the same number of digits for all table entries.

Another good example would be using bootstrapped percentile confidence intervals and checking whether zero is inside it or not. One can supply multiple intervals. Making that kind of output is extremely easy if one uses boot package. However, examples of such style in real scientific journals are virtually unseen—because either their typesetters have not read this entry (yet) and are blissfully unaware of this method, or this sort of acrobatics is not deemed æsthetically pleasing or practical.


\coefbootci[4cm]{0.034}{-0.01}{0.09} \par

It is possible to make any formatting aspect adjustable. The last example shows how to make coefficients significant at 5% bold.


LaTeX conditional formatting based on t statistics

Virgin insignificant coefficient with $t=1.5$: \coefbold{4.20}{2.8} \par
Chad significant coefficient with $t=2.5$: \coefbold{6.66}{2.664}

P.S. In no way is this entry published in order to promote hacking p-values or abusing the data and/or methodology in order to get a sweet succulent p-value that is less than 0.05. Researchers are encouraged to avoid such filthy terms as ‘a convincing trend towards significance’ and other ones, and honestly provide the results as is, using asymptotic refinement via bootstrap, or empirical-likelihood-based with proper calibration, or, in small samples with limited-value variables, exact values for non-parametric small-sample statistics.

18 самых трудных правил и особенностей русского языка для иностранцев

Prepare to take a ride on an emotional roller-coaster across the most challenging aspects of Russian language. Or should I rather correct the previous sentence, “descent into madness”. Some of my French and Luxembourgian friends married some of my Russian friends and are currently learning Russian in order to improve communication with their spouses and show devotion. Naïve martyrs, says me; little do they know that the system of conjugation and declension has so many illogicalities and exceptions that it is easier to say that there is absolutely no system to declension and conjugation. Let’s begin, shall we?

  1. In Russian, if one is narrating a story and wants to emphasise the suddenness of some action, one can substitute the 3rd person past indicative (singular or plural) with the 2nd person present imperative (singular only).
  2. This works in reverse: one can use 2nd person past perfective to denote imperative!
  3. In fact, when narrating, instead of 1st person past continuous, one can use just present (Russian does not have continuous tenses, neither it has present perfective.) However, incidentally, the present tense can also describe future events.

    Шагаю я намедни по плацу, а у меня возьми и отойди пуговица на шинели. Старшина тут же: «Быстро пришил пуговицу обратно!» А я не могу, я встречаюсь с девушкой через час.
    Verbatim translation: I am marching the other day on the drill ground, and suddenly, you, button, imperativego and imperativefly off. Sergeant: “You sewed this button back on!” But I cannot waste time, I have a date in one hour!
    Proper translation: I was marching the other day on the drill ground, and suddenly, a button, decided to fly off. Sergeant: “Hey you, imperativesew this button back on!” But I cannot waste time, I am having a date in one hour!

  4. You know, in some languages, verbs have their own conjugation tables. Enormous tables for every single verb. Like conjugaison.com (from the creators of “j’aurais voulu que vous sussiez” and “vous pûtes”). Some verbs do not necessarily make sense in certain forms (no one would say about themselves “I foal”, which means, to give birth to a colt—a baby horse). Russian has a verb for giving birth to a horse (жеребиться), but does not have its first-person form (жереблюсь? жеребюсь? ожеребляюсь?). Another example is the modification of “to head up” for a wheat spike. If anyone here is wheat spike, raise your awns. Some verbs do not have certain forms because they would just sound awful (бдеть, to keep vigil — бжу? бдю? бдею?; шерстить, to irritate someone’s skin with wool — шерщю? шерстю? шерщиваю?). So in Russian, those verb forms are substituted with ersatz expressions (сохраняю бдительность, я свитер, оттого я чешу и колюсь). Those are called insufficient verbs since they do not have certain forms. Do not be surprised if you cannot simply translate “I shall win” using the future perfective form of the verb “to win” because there is none (variants such as победю, побежу, побежду are all wrong)! You already lost when you started learning Russian.
  5. Conversely, some verbs have two forms (such verbs are called superfluous). Of course, with slightly different meanings; otherwise, where would be fun in that? For example, the verb “cast” would have the same infinitive but different indicative forms: “Zeus casts lightning bolts” (Зевс мечет молнии) and “the athlete throws the hammer” (спортсмен метает молот).
  6. In Russian language, there is a special form of past tense, plus quam perfectum, or pluperfect (which, of course, is not listed in conjugation tables in textbooks dictionaries!), that is analogous to the English “used to / would” or French “avait fait”. However, it is not past perfect in the traditional sense; it denotes a continuous action for which the speaker would like to evoke memories of the distant past. The simple past tense of the verb ходить (to walk) is ходил, but the pluperfect form is хаживал. In it is more or less analogous to the English “would”: “Back in the days of yore, my father would visit royal dinner parties and would try precious wine from Duke’s personal reserves. Oh, the yesteryears! Poor, poor father, where is he now! Those corks on the shelf from the bottles of wine he would savour are the last vestiges of the long-faded grandeur!”

    Говорить — говаривал, петь — певал, сидеть — сиживал, есть — едал, ездать — езживал, гостить — гащивал, обедать — обедывал, драть — дирал, двигать — двигивал, махать — махивал, жить — живывал, гонять — ганивал, спать — сып́ал, кутить — кучивал, бегать — бегивал.

  7. Also, one cannot just say, “there is a glass on the table”. Things on top of other things must either stand, lie, or sit, and there is no rule, logic or mnemonic to determine which verb to use.

    There is a table. There is a glass on the table. It is standing (стакан стоит). There is a fork on the table. It is lying (вилка лежит). However, if we stick the fork into the table, it will be standing (or sticking out; будучи воткнутой в стол, вилка стоит вертикально). Maybe it is the horizontal / vertical orientation that matters? Let’s add a plate and a pan. They are horizontally oriented, but they are still standing (на столе стоят тарелка и сковородка). Now let’s place the plate inside the pan. Now it is lying in the pan (but it had been standing on the table; тарелка лежит в сковородке). The readiness of an object for use is not an indicator: the fork is lying. Not a cat jumps on the table. The cat can stand, sit or lie (кошка стоит, сидит или лежит). It is trivial to connect lying / standing with the cat’s orientation, but sitting? It is a new property. The cat’s bottom is instrumental in sitting (кошка сидит). Now a bird lands on the table. It is sitting as well (птица сидит). However, its legs are fully supporting its body, and in no way the bird is using its botty department. The bird, however, is never standing. Now we go berserk, kill the bird, and a taxidermist (probably Chuck Testa) stuffs it and makes a completely life-like bird—and now it is standing (чучело птицы стоит)! If you think that only animate object can sit, you are wrong again: a shoe sits on a foot, a dress sits on a person, a car sits in snow, a mosquito sits in amber (ботинок сидит на ноге, платье сидит на человеке, машина сидит в сугробе, комар сидит в янтаре). These objects are inanimate, do not have buttocks, but still, they are sitting! Now go figure out which objects sit, which stand, and which lie.

    The Staffordshire department of the Royal Society of Putting Things on Top of Other Things must have accepted too many Russian members!

  8. In Russian, plural is denoted in three possible ways: singular nominative, singular genitive, and... well, plural. It goes like this:
    One cow, two ofcow, three ofcow, four ofcow, five cows, six cows... eleven cows, fourteen cows, and so it goes on until twenty cows. Then... you have twenty-one cow. Because it ends with one! Then, twenty-two... you guessed right... ofcow! Twenty-four ofcow, twenty-five cows, and so it goes on. Everyone remembers Disney’s “101 dalmatian”, right?

  9. A small but nasty one: while the words for 20, 30, 50, 60, 70, 80 and 90 are based on 2, 3, 5, 6, 7, 8 and 9 respectively (like two-ten, three-ten etc.), the word for 40 (сорок) does not have anything related to four. Instead, it is related to.... packed bundles of sable fur, why not! It is not the word forty that Russians used to describe the number of sable pelts in a bundle sufficient to make one coat; it is literally the word “cloth to wrap a bundle of sable pelts” that Russians use for forty! The closest relative of this atrocity is the word сорочка (a shirt made of cloth), which is widely used as a synonym for рубашка.

    Russia Reversal meme about numeral for forty

    Bulgarians did not have sables or martens, so in Bulgarian language (which is re-e-eally close to Russian), they use Russian numerals two-twenty, three-twenty, four-twenty, five-twenty etc. No animals harmed.

  10. Worse than that, with compound numerals (like three thousand five hundred and seventy-four), one has to decline every word of the numeral. Sometimes, if a numeral is one word made of two parts (like “four-hundred”), you have to decline both. Or maybe not. Of course, if the numeral in question is fourteen, you do not decline the four, because screw fourteen! And two-ten, three-ten and four-ten as well. So it will look like this:

    Я гордый владелец трёх тысяч пятисот семидесяти четырёх коров.
    Я гордый владелец трёх тысяч трёхсот тридцати четырёх коров.
    Я гордый владелец трёх тысяч семисот четырнадцати коров.

    I am a proud owner ofthree ofthousand offiveofhundred ofsevenoften offour ofcows.
    But! I am a proud owner ofthree ofthousand ofthreeofhundred threeoften ofthree ofcows.
    But! I am a proud owner ofthree ofthousand ofsevenofhundred fourofteen ofcows.

    Oh, and did I tell you that you have four more cases to remember for these numerals?

  11. To make things worse, numerals ending with 1 or 2 can have genders in the nominative case. But only masculine or feminine. No neuter.

    Два чайника, две чашки, два пальто.

  12. Speaking of genders, verbs have genders in the past, but not in the present or future.

    Металл кипел, сталь кипела, железо кипело, жидкости кипели.

  13. Russian has different declension rules for animate and inanimate objects. However, a stiff is animate, while a corpse is not. Why? Well, only a human being can be a stiff, but corpses can also be of animal origins... so it makes dead animals less animate than dead humans? I hypothesise that this dates back to Russian folk tales in which stiffs came to life after being sprinkled with the Water of Life™ (they also featured the Water of Death™ that was used to join together the pieces of a fallen hero). However, the more logical reasoning is the following: the word мертвец (stiff) has a tinge of “freshness” (just died), maybe clinical death, someone who had just died, but the word труп (corpse) denotes something that has been dead for a while. One does not exhumate stiffs; only corpses. In official language (forensic reports) one might use the collocation свежий труп (fresh corpse) to indicate that the body has not begun to rot yet.

    Я вижу на земле мертвеца. (Accusative taking the form of genitive, as with animate objects.)
    Я вижу на земле труп. (Accusative taking the form of nominative, as with inanimate objects.)

  14. You thought it was over, huh? Cue fractional numerals! You all know that 8 metres should always be “eight metres”, no silly gobbledegook like “three ofcow”? Well... if it is 8.6 metres, it has to be spelt “eight and six tenths... ofmetre”, because it is the bloody tenths that govern the declension “of metre”! However, if one means “8½ metres”, it becomes “eight and a half metres”. Did I say that while “my pie” is singular, “my half a pie” is plural? Like “ton gâteau” but “tes demi-gâteaux”!
  15. Speaking of numerals. Most languages have cardinal numerals and ordinal numerals. However, Russian also has collective animate masculine numerals that sometimes describe groups of men, occupations (but possibly females), and uncountable singular nouns! One can’t say “two ofman”. One must say “two-group men”. Then, “three-group men”, up to “nine-group men”, although one can use the simple cardinal plural starting from 5. And one must not use collective numerals for groups larger than 10.
  16. And some countable nouns have absolutely mental plural forms: дно — донья (bottom; almost like doña), брелок — брелоки (keychain, but чулок — чулки, stocking), шило — шилья (awl), профессор — профессора (professor). It gets better with genitive: кочерга — кочерёг (hot poker), кровля — кровель (roofing), усадьба — усадеб (manor), вафля — вафель (waffle), цапля — цапель (heron), кегля — кегель (bowling pin), but кегль — кеглей (typographic unit, from German Kegel).
  17. If you thought it does not get worse, brace yourselves. Look at the word “human”. Look at it closely? Do you think it has two forms of plural, cardinal and collective? Well, here you are wrong again: three plural forms! It has collective plural (nobody matters), tally plural (each one matters), and archaic plural (for greater grandiloquence). It is like distinguishing between “many people”, “a number of individuals” and “humanity”. (One could parry that kind of attack on sanity with an over-the-top number of collective nouns in the post-Norman tongue...)

We are approaching the culmination, or, as Kaikosru Sorabji would put it, “the crux”. Combining together muddy numerals and incoherent declension, one gets a new frankenrule:
If the numeral ends with 1, 2, 3 or 4, one uses singular declension rules to denote multiplicity. However, in cases other than nominative, one uses plural for those one ending with 2, 3 or 4. If one thinks of those objects as of a large group performing an action, instead of the plural form of the verb, one can use the neuter singular! However, if the numeral ends with 1, one must use the singular form of the verb of the appropriate gender!

Declension of numerals in Russian

I did not make this up. This is true. Denoting accusative with den, as in German, we get the example to illustrate it:

Сто один далматинец переходил дорогу. Грузовик сбил сто одного далматинца.
Сто два далматинца переходило / переходили дорогу. Грузовик сбил сто двух далматинцев.
Сто пять далматинцев переходило / переходили дорогу. Грузовик сбил сто пять / пятерых далматинцев.

One hundred and one dalmatian was crossing the highway. The lorry ran over hundred and denone dendalmatian.
One hundred and two ofdalmatian was/were crossing the highway. The lorry ran over denhundred and dentwo dendalmatians.
One hundred and five dalmatians was/were crossing the highway. The lorry ran over denhundred and denfive / denfive-group dendalmatians.
(Here, one cannot say “сто двоих”, hundred and two-group, because it would mean, “hundred and both”!)

I have no words. The only thing I have is an back-of-the-envelope estimate: if kids start learning Russian at the age of 0 and by the age of 18, having graduated from high school, are aware of all these pitfalls, then it would take 18 years of intense learning (like at school, multiple hours per day of reading textbooks in Russian, watching TV, communicating with native speakers etc.) to master Russian. If you are a non-Russian reading this, the only way to comprehend Russian grammar is marrying a Russian and learning the language with your kid. By the time they reach the age of majority, you will be able to speak as fluently as they.

How to set up a Linux computer and printers at the University of Luxembourg

NB: This is not the official guide. This is a summary of my Linux adventures at the University of Luxembourg. I am not affiliated with the IT department of Uni.LU. For actual help, please create tickets in the service portal; I am not offering advice!

First of all, I would like to thank the IT department of the University of Luxembourg for not upgrading to Windows 10. I lack words with which to express my vitriol and execration for Windows 8, but this is a topic for another post. However, not fully happy with Windows 7, I decided to create a dual-boot system (Windows 7 / Linux). The only thing remaining was partitioning the hard drive. In order to shrink the volume, Windows obliged me to do a Disk Check using CHKDSK. And this is where it went downhill. After a reboot, CHKDISK spent the entire night restoring chunks of god-knows-what, then rebooted the computer, started the Start-Up Recovery (who was asking for those options anyway?!), tried to fix the boot loader, froze and... broke the Windows boot loader. Enough is enough.

Margaret Thatcher Enough Is Enough

First of all, I made sure that Linux has all the necessary built-in drivers for Ethernet and the Internet connection is fine. For that purpose I downloaded Linux Mint 19 64 bit with Cinnamon, wrote it onto a USB stick on my Mint 19 laptop (with USB Image Writer, mintstick), and booted from the USB, and verified that the Internet does not require any extra configuration (VPN, PPPoE etc.) and works out of the box. I made a backup of all my documents, asked the IT department to flush the computer completely, and then, shrunk the C:\ drive by 200 GB (100 GB for /, 96 GB for /home, 4 GB for swap).

I decided to go with Arch Linux because I did not want any unnecessary software or dæmons running in the background. However, I cheated a bit and installed Linux Mint first (partitioning the hard drive with the graphical tool in Mint installer), and then, used /dev/sda5 and /dev/sda6 as / and /home respectively in Arch Linux installer. The only unexpected thing was the necessity to launch dhcpcd manually. After that, I got the core packages, installed Xorg, LightDM, and then, Cinnamon.

Linux printing on Uni.Lu computers

Since the University of Luxembourg is using Windows print servers (damn!), one must use CUPS and SAMBA in order to send jobs. They recommend installing system-config-printer as the GUI and then going through the following steps:

  1. System settingsPrinters or Print SettingsAddNetwork PrinterWindows Printer via SAMBA.
  2. SMB Printer: smb://PRINTSERVER.uni.lux/PRINTERNAME.
    Example: smb://woodstock.uni.lux/CL-ENTE
  3. Authentication details (do not press Verify):
    Username: uni.lux\FIRSTNAME.LASTNAME
    Password: your UNI.LU password
  4. Press Forward, select the printer model* and find the generic PCL6 driver (recommended in general) and press Apply.
  5. Do not print a test page since the proper paper size is still not set.
  6. Right-click on the printer, select Properties, go to Printer options and select A4 as the paper size.

* If the printer model is not in the list of available models, make sure that the driver is installed. If the maker is Canon, you can find Canon DEB/RPM drivers on the official Canon support website; Arch Linux has cndrvcups-lb in AUR, and for a other Linux distributions, you need to get the PPD file for the printer model you are going to install. Many common printer models are supported by the Gutenprint driver collection (cupsys-driver-gutenprint in Debian, gutenprint in Arch).

If, when printing for the first time, the user is prompted for their name, the ID must be in the form of uni.lux\firstname.lastname.

If you are located in Belval, JFK or Limpertsberg, the print server is woodstock. If you are located in Kirchberg or Weicker, the print server is baloo.

Remark: you can have access to Canon printers for all sites located mainly in the corridors using the print server ares. In this case, you can choose: smb://ares.uni.lux/WIN_CANON_BLACK, smb://ares.uni.lux/WIN_CANON_COLOR, or smb://ares.uni.lux/WIN_CANON_DUPLEX. Then, on the Canon printer itself, log on and select the file to print.

If you do not have the system-config-printer package installed in your Linux distribution, make sure that the packages cups and samba iares installed and the CUPS and SAMBA dæmons are running (most likely to be named cups and smbd in Debian-based distros, org.cups.cupsd.service and smb.service in Arch-based etc.). Then, you can add the printer via the CUPS local web interface (the true Linux way!):

  1. Go to
  2. Click Add Printer and, if prompted, enter root as the username and your root password. (If you input the wrong credentials and get the Forbidden error, just reboot your computer.)
  3. Pick Other Network PrintersWindows Printer via SAMBA.
  4. In the Connection field, enter smb://uni.lux\FIRSTNAME.LASTNAME:PASSWORD@PRINTSERVER.uni.lux/PRINTERNAME.
    Example: smb://uni.lux\rupert.hastings:password123@woodstock.uni.lux/CL-ENTE
  5. Optionally, give the printer a user-friendly name and a description.
  6. Select the manufacturer and the model. (If the printer is not in the list, see the footnote above.)
  7. If extra accessories are installed on the printer (puncher, extra paper trays etc.), select them in the next step.

Email client

The University of Luxembourg is using IMAP for incoming mail and SMTP for outcoming. Here is a list of parameters you have to supply to your client in order to be able to receive and send messages. So far, I managed to configure Mozilla Thunderbird, Mutt, and NeoMutt.


  • IMAP server: imaps://imap4-3.uni.lu:993
  • Connection security: SSL/TLS
  • Default folder: INBOX


  • SMTP user: same as IMAP user
  • SMTP password: same as IMAP password
  • SMTP server: smtp-3.uni.lu:587
  • SSL force TLS: yes

Server space on Atlas

  1. Make sure your workgroup is WORKGROUP (if necessary, put workgroup = WORKGROUP in /etc/samba/smb.conf). Next, make sure that gvfs-backends (Debian) gvfs-smb (Arch) is installed.
  2. Open your favourite file browser (Nautilus, Nemo etc.) and go to the following address in the address bar: smb://atlas/users/FIRSTNAME.LASTNAME.
  3. Example: smb://atlas/users/rupert.hastings.
  4. When prompted, enter your credentials. Username: FIRSTNAME.LASTNAME. Domain: uni.lux. Password: your UNI.LU password.

To be perfectly honest, I have not been able to open any folder other than the root (atlas)!

Finally, after looking at the Quick Start Guide provided by the IT staff, I would suggest ignoring some items, like:

  • Microsoft Office 365 and Dreamspark. Who needs it? Just use LibreOffice. Do not use MS Word. Use LibreOffice Writer for short documents and LaTeX for long ones.
  • Eduroam configuration. If you have a wired connection, just use it. Otherwise, go to https://cat.eduroam.org and download the necessary SH script.
  • VPN. https://vpn.uni.lu.

Stochastic portfolio optimisation and out-of-sample testing using R

Author: Andreï Victorovitch Kostyrka, University of Luxembourg.

Last updated: 2018-07-31.

One might ask a question, “What is it like to try to pick an optimal portfolio and invest in stocks?” Well, here I have prepared some R code that does the following thing:

  • Downloads stock data from Yahoo Finance from 2014 for a selection of stocks;
  • Puts all stocks together across the maximum set of available dates and nicely imputes missing values using Kalman filter with structural modelling;
  • Tries all possible combinations or portfolios (as many as possible, using Halton pseudo-random low-discrepancy sequences, doing many iterations and saving the best result from every iteration to save memory);
  • Creates amazing colourful plots for subsequent analysis;
  • Returns statistics for equally weighted portfolios, max-return under equally weighted risk, min-risk under equally weighted return, and maximum Sharpe ratio (for simplicity, the ratio of returns to risk, assuming there is no risk-free asset);
  • Tests these 4 portfolios out of sample for 1 year (“if one started trading one year ago, what would one have obtained”).

Two sets of stocks were chosen: most lucrative U.S. companies and most lucrative Russian companies. This is what one gets if one chooses 13 top U.S. companies:

library(imputeTS) # For imputation
library(randtoolbox) # For Sobel sampling
# http://fortune.com/2017/06/07/fortune-500-companies-profit-apple-berkshire-hathaway/
# https://www.swiftpassportservices.com/blog/profitable-companies-russia/
syms <- c("GOOG", "AAPL", "JPM", "BRK-A", "WFC", "MCD", "BAC", "MSFT", "AMZN", "JNJ", "C", "MO", "GE")
symnames <- c("Google", "Apple", "J.P. Morgan", "Berkshire Hathaway", "Wells Fargo", "McDonald's",
              "Bank of America", "Microsoft", "Amazon", "Johnson and Johnson", "Citigroup", "Altria group", "General Electric")
cat("Calculating optimal portfolio for US stocks\n")
# syms <- c("SGTZY", "ROSN.ME", "OGZPY", "LUKOY", "SBRCY", "TRNFP.ME", "NILSY", "ALRS.ME", "YNDX")
# symnames <- c("SurgutNefteGas", "RosNeft", "GazProm", "LukOil", "SberBank", "TransNeft",
#               "Norilsk Nickel", "Alrosa", "Yandex")
# cat("Calculating optimal portfolio for Russian stocks\n")
first.date <- as.Date("2014-01-01")
last.date <- as.Date("2018-08-01")
end.ins <- as.Date("2017-08-01")
dat <- BatchGetSymbols(tickers = syms, first.date = first.date, last.date = last.date)
allt <- dat$df.tickers
allt <- allt[!is.na(allt$price.adjusted), ]
dates <- sort(unique(allt$ref.date))
prices <- data.frame(dates)
prices[, 2:(length(syms)+1)] <- NA
colnames(prices)[2:(length(syms)+1)] <- syms
for (i in syms) {
  datesi <- allt$ref.date[as.character(allt$ticker)==i]
  pricesi <- allt$price.adjusted[as.character(allt$ticker)==i]
  prices[match(datesi, dates), i] <- pricesi
  prices[, i] <- zoo(prices[, i], order.by = prices$dates)
  prices[, i] <- na.kalman(prices[, i])
prices2 <- prices
prices[,1] <- NULL
co <- rainbow(length(syms), end=0.75)
png("1-relative-prices.png", 700, 400, type="cairo")
plot(prices[,1]/mean(prices[,1]), col=co[1], lwd=1.5, main="Prices divided by their in-sample mean", xlab="Time", ylab="Ratio")
for (i in 2:length(syms)) {
  lines(prices[,i]/mean(prices[,i]), col=co[i])
legend("topleft", syms, col=co, lwd=1)
rs <- data.frame(rep(NA, nrow(prices)-1))
for (i in syms) {
  rs[, i] <- diff(log(prices[, i]))
rs[,1] <- NULL
w0 <- rep(1/length(syms), length(syms))
names(w0) <- syms
rmean <- zoo(as.numeric(as.matrix(rs) %*% w0), order.by = time(rs[,1]))
a <- table(as.numeric(format(time(rmean), "%Y")))
daysperyear <- mean(a[1:(length(a)-1)]) # Because the last year is incomplete
rsfull <- rs # Full sample
rs <- rs[time(rs[,1]) <= end.ins, ] # Training sample
rsnew <- rsfull[time(rsfull[,1]) > end.ins, ] # Test sample
meanrs <- colMeans(rs)
covrs <- cov(rs)
musigma <- function(w) {
  mu <- sum(meanrs * w)*daysperyear
  s <- sqrt((t(w) %*% covrs %*% w) * daysperyear)
  return(c(mu=mu, sigma=s, ratio=mu/s))
m0 <- musigma(w0)
num.workers <- if (.Platform$OS.type=="windows") 1 else detectCores()
MC <- 108000
iters <- 100
cc <- 150 # How many colours
cols <- rainbow(cc, end = 0.75)
sharpecuts <- seq(-0.1, 1.5, length.out = cc)
png("2-portfolios.png", 700, 600, type="cairo")
# First iteration
cat("Calculating", MC, "portfolios for the first time.\n")
ws <- halton(MC, length(syms), init=TRUE)
ws <- ws/rowSums(ws)
colnames(ws) <- syms
res <- mclapply(1:MC, function(i) musigma(ws[i, ]), mc.cores = num.workers)
res <- as.data.frame(matrix(unlist(res, use.names = FALSE), nrow=MC, byrow = TRUE))
colnames(res) <- c("mean", "sd", "ratio")
prcmu0 <- ecdf(res$mean)(m0[1]) # Which quantile is the mean
prcsd0 <- ecdf(res$sd)(m0[2]) # Which quantile is the sd
qmplus <- quantile(res$mean, prcmu0+0.005)
qmminus <- quantile(res$mean, prcmu0-0.005)
qsplus <- quantile(res$sd, prcsd0+0.005)
qsminus <- quantile(res$sd, prcsd0-0.005)
meanvicinity <- which(res$mean < qmplus & res$mean > qmminus)
sdvicinity <- which(res$sd < qsplus & res$sd > qsminus)
plot(res[,2:1], pch=16, col=cols[as.numeric(cut(res$ratio, breaks = sharpecuts))],
     xlim=range(res$sd)+c(-0.03, 0.03), ylim=pmax(range(res$mean)+c(-0.03, 0.03), c(0, -10)),
     main="Risk and return for various portfolios", xlab="Annualised volatility", ylab="Annualised log-return")
sharpes <- mus <- sds <- array(NA, dim=c(iters+1, length(syms)))
sharpes[1, ] <- ws[which.max(res$ratio), ]
mus[1, ] <- ws[which(res$mean == max(res$mean[sdvicinity])), ]
sds[1, ] <- ws[which(res$sd == min(res$sd[meanvicinity])), ]
pairsm <- pairss <- array(NA, dim=c(iters+1, 3))
pairsm[1, ] <- res$mean[c(which.max(res$ratio), which(res$mean == max(res$mean[sdvicinity])), which(res$sd == min(res$sd[meanvicinity])))]
pairss[1, ] <- res$sd[c(which.max(res$ratio), which(res$mean == max(res$mean[sdvicinity])), which(res$sd == min(res$sd[meanvicinity])))]
for (i in 1:iters) {
  cat("Calculating", MC, "portfolios, iteration", i, "out of", iters, "\n")
  # ws <- sobol(MC, length(syms), scrambling = 1, init=FALSE) # There is a bug in randtoolbox: it starts returning numbers outside [0, 1]
  ws <- halton(MC, length(syms), init=FALSE)
  ws <- ws/rowSums(ws)
  colnames(ws) <- syms
  res <- mclapply(1:MC, function(i) musigma(ws[i, ]), mc.cores = num.workers)
  res <- as.data.frame(matrix(unlist(res, use.names = FALSE), nrow=MC, byrow = TRUE))
  colnames(res) <- c("mean", "sd", "ratio")
  meanvicinity <- which(res$mean < qmplus & res$mean > qmminus)
  sdvicinity <- which(res$sd < qsplus & res$sd > qsminus)
  maxsh <- which.max(res$ratio)
  maxm <- which(res$mean == max(res$mean[sdvicinity]))
  minsd <- which(res$sd == min(res$sd[meanvicinity]))
  sharpes[i+1, ] <- ws[maxsh, ]
  mus[i+1, ] <- ws[maxm, ]
  sds[i+1, ] <- ws[minsd, ]
  pairsm[i+1, ] <- res$mean[c(maxsh, maxm, minsd)]
  pairss[i+1, ] <- res$sd[c(maxsh, maxm, minsd)]
  points(res[,2:1], pch=16, col=cols[as.numeric(cut(res$ratio, breaks = sharpecuts))])
  rm(res); gc()
points(as.numeric(pairss), as.numeric(pairsm))
sharpems <- apply(sharpes, 1, musigma)
wmaxsharpe <- sharpes[which.max(sharpems[3,]), ]
meanms <- apply(mus, 1, musigma)
wmaxmean <- mus[which.max(meanms[1,]), ] # Maximum returns while SD is the same
sdms <- apply(sds, 1, musigma)
wminsd <- sds[which.min(sdms[2,]), ] # Minimum SD while mean is the same
m1 <- musigma(wmaxsharpe)
m2 <- musigma(wmaxmean)
m3 <- musigma(wminsd)
finalstats <- cbind(rbind(w0, wmaxsharpe, wmaxmean, wminsd), rbind(m0, m1, m2, m3))
rownames(finalstats) <- c("Equal", "MaxSharpe", "MaxReturn", "MinRisk")
colnames(finalstats)[(length(syms)+1):(length(syms)+3)] <- c("RInS", "VInS", "SRInS")
points(m0[2], m0[1], cex=3, pch=16)
points(c(m1[2], m2[2], m3[2]), c(m1[1], m2[1], m3[1]), cex=2, pch=16)
# And now checking these revenues on the test sample
r0 <- zoo(as.numeric(as.matrix(rsnew) %*% w0), order.by = time(rsnew[,1]))
r1 <- zoo(as.numeric(as.matrix(rsnew) %*% wmaxsharpe), order.by = time(rsnew[,1]))
r2 <- zoo(as.numeric(as.matrix(rsnew) %*% wmaxmean), order.by = time(rsnew[,1]))
r3 <- zoo(as.numeric(as.matrix(rsnew) %*% wminsd), order.by = time(rsnew[,1]))
png("3-test-sample-returns.png", 700, 400, type="cairo")
plot(r0, main="Out-of-sample returns of weighted portfolios", ylab="Return", xlab="Time")
lines(r1, col=2)
lines(r2, col=3)
lines(r3, col=4)
legend("topright", c("Equal", "Sharpe", "Max. return", "Min. volatility"), col=1:4, lwd=1)
png("4-test-sample.png", 700, 400, type="cairo")
plot(exp(cumsum(r0)), ylim=c(0.6, 1.4), main="Portfolio growth over the last year in the test sample", ylab="Relative growth", xlab="Time")
lines(exp(cumsum(r1)), col=2)
lines(exp(cumsum(r2)), col=3)
lines(exp(cumsum(r3)), col=4)
legend("bottomleft", c("Equal", "Sharpe", "Max. return", "Min. volatility"), col=1:4, lwd=1)
finals <- cbind(r0, r1, r2, r3)
meanf <- colMeans(finals)*daysperyear
sdf <- apply(finals, 2, sd)*sqrt(daysperyear)
finalsoos <- cbind(meanf, sdf, meanf/sdf)
colnames(finalsoos) <- c("ROOS", "VOOS", "SRROS")
finalstats <- cbind(finalstats, finalsoos)
colnames(finalstats)[1:length(syms)] <- symnames
stargazer(t(finalstats), summary = FALSE, type="html", out="a.html")
write.csv(prices2, "stocks.csv", row.names = FALSE)

This is how the 13 U.S. stocks behaved.

Relative prices of top U.S. stocks

This is how 10 million random portfolios behaved (black dots indicate 100 best portfolios under the three criteria; big black dot for the equally weighted portfolio).

Return and risk of various U.S. portfolios

These are portfolio weights for U.S. companies with their performance.

Equal MaxSharpe MaxReturn MinRisk
Google 0.077 0.011 0.004 0.052
Apple 0.077 0.132 0.128 0.105
J.P. Morgan 0.077 0.133 0.099 0.028
Berkshire Hathaway 0.077 0.019 0.040 0.170
Wells Fargo 0.077 0.003 0.008 0.025
McDonald's 0.077 0.164 0.148 0.192
Bank of America 0.077 0.030 0.034 0.036
Microsoft 0.077 0.078 0.180 0.022
Amazon 0.077 0.088 0.161 0.005
Johnson & Johnson 0.077 0.138 0.064 0.138
Citigroup 0.077 0.003 0.003 0.009
Altria group 0.077 0.198 0.131 0.142
General Electric 0.077 0.003 0.001 0.078
Return in-sample 0.145 0.179 0.190 0.145
Risk in-sample 0.142 0.128 0.141 0.119
Sharpe ratio in-sample 1.023 1.395 1.345 1.217
Return in 2017.07–2018.06 0.135 0.163 0.241 0.053
Risk in 2017.07–2018.06 0.144 0.134 0.146 0.130
Sharpe ratio in 2017.07–2018.06 0.941 1.218 1.657 0.404

This is how these four U.S. portfolios look out of sample.

Returns for different optimal U.S. portfolios out-of-sample

If one had invested in these four portfolios a year before, this is what one would have harvested by now.

Cumulative growth of one's investments into U.S. stocks

And this is the result for top 9 Russian companies.

This is how the 9 Russian stocks behaved.

Relative prices of top Russian stocks

This is how 10 million random portfolios behaved (black dots indicate 100 best portfolios under the three criteria; big black dot for the equally weighted portfolio).

Return and risk of various Russian portfolios

Note that some portfolios can actually yield negative returns, and the volatility is generally higher!

These are portfolio weights for Russian companies with their performance.

Equal MaxSharpe MaxReturn MinRisk
SurgutNefteGas 0.111 0.005 0.009 0.175
RosNeft 0.111 0.162 0.031 0.269
GazProm 0.111 0.012 0.068 0.067
LukOil 0.111 0.018 0.083 0.037
SberBank 0.111 0.038 0.031 0.014
TransNeft 0.111 0.248 0.016 0.213
Norilsk Nickel 0.111 0.079 0.381 0.044
Alrosa 0.111 0.413 0.358 0.049
Yandex 0.111 0.026 0.022 0.131
Return in-sample 0.055 0.227 0.172 0.055
Risk in-sample 0.245 0.218 0.245 0.218
Sharpe ratio in-sample 0.223 1.042 0.701 0.250
Return in 2017.07–2018.06 0.202 0.164 0.223 0.164
Risk in 2017.07–2018.06 0.179 0.170 0.215 0.153
Sharpe ratio in 2017.07–2018.06 1.129 0.965 1.039 1.067

This is how these four Russian portfolios look out of sample.

Returns for different optimal Russian portfolios out-of-sample

If one had invested in these four portfolios a year before, this is what one would have harvested by now.

Cumulative growth of one's investments into Russian stocks

So actually if one used this investing strategy based on the information available in mid-2017, by now, depending on the criterion (Sharpe ratio or maximum profitability) they would have earned 14–22% on Russian stocks or 15–17% on American stocks!

TODO: constrained optimisation using the best stochastic solution as a starting point.


Why are you still here? Why are you not trading yet?

Using Twitter to model voters’ attitude towards presidential candidates: a case for Russia in 2018

NB. Any opinions that might be critical of the political system of Russia are justified by the fact that the author is a citizen of Russia himself, and retains the right to give opinions, or commentary, or judgement.


Twitter has been known to serve as a news publication machine that drives the attention of mass media and shapes the preferences of voters; a good example of this would be the presidential elections in the USA in 2016 (Kapko, 2016). Presidential candidates were using this medium to communicate to voters directly and express their opinions outside presidential debates. It has been speculated that predictions made based on Twitter data can perform better than those obtained by robocalls or by examining the distribution of lawn signs.

Sometimes, as in the case with Donald Trump, using free-wheeling speech style can be really beneficial because it reassures voters that their candidates speaks what (s)he thinks. Candidates' tweets are news per se, and news agencies can easily get the low-hanging fruit by just re-publishing them and giving their own interpretation. Besides that, Twitter provides an opportunity to engage into a direct dialogue between the candidates and voters via the feature of directed tweets. Celebrities and influential people often respond directly to the candidates, which drives the evolution of voters' views. It has been noted that often it is clear who is writing the tweet: the candidate him/herself or his/her staffers.

As good as it may sound, there are obvious drawbacks to Twitter. First and foremost, it seems almost impossible to fit a meaningful argument within the limit of 140 (now 280) characters. As a result, it causes oversimplification of discourse. Another point is debatable: as soon as something is posted on Twitter, it is impossible to fully withdraw the tweet if someone else has noticed it. This can be both a drawback and a strong point: as soon as lewd material is posted, the poster bears full responsibility for it, and experiences all potential backlash.

Twitter as a predictor for election results has been rigorously analysed by researchers in the past. In fact, such analyses were applied to the 2010 Australian elections (Burgess and Bruns, 2012), 2010 Swedish elections (Larsson and Moe, 2012), 2011 Dutch elections (Sang and Bos, 2012), 2012 USA elections (Wang et al., 2012), 2015 Venezuelan elections (Yang, Macdonald and Ounis, 2017), 2016 USA elections (Bessi and Ferrara, 2016) etc. Some of them are using convolutional neural networks, some of them are applying clever tools to avoid misclassification, but some of them rely on a simple count of words from positive and negative dictionaries. We are going to adopt this simple approach in an attempt to analyse Russian data and evaluate the balance of powers (or lack thereof) in Russia.

In this work, I am using big data (70 000 tweets in total) and big data processing tools (Google Translate API) to investigate the relative popularity of candidates in the Russian presidential election of 2018. The methodology will be similar to that of Bhatia (2015).


In this work, I develop a simple method to analyse the sentiment towards election candidates in arbitrary languages using Google Translate. It should be noted that as the moment of writing, Google is offering a free $300 trial for its Cloud API, so the author made use of his free access to the machine translation services. The workflow is as follows:

  1. Using R and twitteR package, obtain a large number (10 000) tweets mentioning the candidate;
  2. Break the tweets into small batches (100 tweets per batch separated with triple paragraphs) and write scripts for translation;
  3. Using Google Cloud Translation API, run the translation scripts and obtain the server response as a JSON object;
  4. Input the JSON object into R, break it into separate tweets again and clean up the text;
  5. Count the positive and negative words in those tweets using dictionaries and analyse the distributions.

Obviously, the main drawback of the simple dictionary match is the lack of context. There are examples of why this might return wrong results. Example 1: “Mr. X is going to put an end to corruption!” This author has a positive attitude towards Mr. X, but due to the presence of a negative word (“corruption”), is going to be counted as negative. Example 2: “@newsagency Yes, of course, Mr. Y is going to improve the situation, yeah, like, thousand times!” This is an example of irony; the attitude of this tweet is negative and sceptical, but the simple count will find a positive match (“improve”) and count this tweet as positive. Example 3: “Mr. Z is not honest!”

To counter these three points, an argument should be made. The error from the first category does not change much in terms of emotional attitude; if candidate X is viewed as a corruption fighter, the writer implies that the situation in the country is grave (hence the need to fight), and this negative score should be counted towards the general level of negativity, not just the negativity associated with candidate X. If candidates Y and Z also claim they are going to fight corruption, then all these negative votes will contribute to a fixed proportion of false negatives (say, n%), and the ratio of negative to positive votes should not change. This implies that ratios, not absolute values should be examined. The error from the second category is so semantically complicated that is it improbable that any advanced methods (including machine learning and neural networks) based on pure text analysis are going to detect irony and correctly interpret it in a negative sense. However, the proportion of such tweets is thought to be low, and an advanced user-based analysis is suggested in this case: if a user is generally opposing candidate Y (or is pessimistic in general), then any tweets with positive score about candidate Y should be re-weighted or discarded as “implausible”. The error from the third category, however, can be remedied with the use of multi-layered neural network or contextual analysis algorithms with look-ahead and look-behind: if the word from the “positive” list is preceded by “not”, “no”, “barely” or followed by “my a**” or other similar modifiers, the match should be counted for the “negative” list, and vice versa.


Searching for tweets

Assumption 1. During the period from 2018-01-01 to 2018-03-18, any tweet containing the surname of a candidate is meant to be about the candidate, not his namesake.

This assumption allows us to identify tweets about the presidential candidates by a simple search using the name of the candidate. The candidates seem to have quite unique surnames, and almost all media covering people with their surnames are covering namely those people.

Assumption 2. There is no bias in Twitter search results; i. e., Twitter is not being in favour of any candidate, or is not filtering negative search results, or is not affected by spam bots who praise candidates.

This assumption is crucial for the unbiasedness of our results; so far, there have been no signs of Twitter censorship in Russia. However, there might be a population bias: people who are using Twitter can turn out to be younger and more progressive, and therefore, more opposing to the current political leader, Putin. It means that whereas most tweets about Putin on Twitter can come from a minority of political opposition, the majority of Putin voters are budget-depending elderly people and beneficiaries who live in faraway regions without internet access or any desire to express their opinions publicly.

api_key <- "..."
api_secret <- "..."
access_token <- "..."
access_token_secret <- "..."
setup_twitter_oauth(api_key, api_secret, access_token, access_token_secret)
find1 <- "Путин"
find2 <- "Бабурин"
find3 <- "Грудинин"
find4 <- "Жириновский"
find5 <- "Собчак"
find6 <- "Сурайкин"
find7 <- "Титов"
find8 <- "Явлинский"
find9 <- "Навальный"
finds <- c(find1, find2, find3, find4, find5, find6, find7, find8, find9)
number <- 10000
tweet1 <- searchTwitter(find1, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet2 <- searchTwitter(find2, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet3 <- searchTwitter(find3, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet4 <- searchTwitter(find4, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet5 <- searchTwitter(find5, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet6 <- searchTwitter(find6, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet7 <- searchTwitter(find7, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet8 <- searchTwitter(find8, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
tweet9 <- searchTwitter(find9, n=number, lang="ru", since="2018-01-01", until="2018-03-18")
save(tweet1, tweet2, tweet3, tweet4, tweet5, tweet6, tweet7, tweet8, tweet9, file="tweets.RData")

Breaking the tweets for translation

A simple snippet of code is suggested below to translate the long and heavy objects on Google Translate. As we know, Google charges API users on a character basis (as of writing, $20 per 1 million characters), with virtually no limit for translation (if the proper quotas are set to be infinite). However, just in order to be sure that the translations are made in time and no information is lost, we broke the messages into blocks of 100 tweets.

byhow <- 100
for (cand in 1:9) {
  texts <- get(paste0("tweet", cand))
  blocks <- ceiling(length(get(paste0("tweet", cand)))/byhow)
  for (i in 1:blocks) {
    sink(paste0("scripts", cand, "/scr", i, ".sh"))
    fr <- byhow*(i-1)+1
    to <- byhow*(i-1)+byhow
    curl -s -X POST -H "Content-Type: application/json" \\
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \\
    --data "{
      \'q\': \'
      if (to > length(texts)) to <- length(texts)
      for (j in fr:to) {
        a <- texts[[j]]$text
        a <- gsub("['\"`]", "", a)
      \'source\': \'ru\',
      \'target\': \'en\',
      \'format\': \'text\'
    }" "https://translation.googleapis.com/language/translate/v2"

Therefore, for each of the nine candidates, it will write out up to 100 script files into a corresponding folder.

Using Google Translate API

Once the script files, titled scr1.sh, ..., scr100.sh are ready, all that remains is run them in series with a time-out (since Google API has a character-per-minute quota).

for i in {1..100}
  echo "Processing tweet file $i of 100"
  ./scr$i.sh > out$i.txt
  sleep 12

This script must be run in every folder (1–9), and the translation results will be stored in files out1.txt, ..., out100.txt (or up to the number of tweets divided by 100 if the candidate was not very popular).

Merging the objects into tweet lists

A simple for loop (for 9 candidates, from 1 to the number of output files) is required to merge the data back.

alltrans <- list()
for (cand in 1:9) {
  lf <- list.files(paste0("./scripts", cand, "/"))
  lf <- lf[grep("out", lf)]
  howmany <- length(lf)
  alltrans[[cand]] <- list()
  for (i in 1:howmany) {
    a <- fromJSON(readLines(paste0("scripts", cand, "/out", i, ".txt")))
    a <- a[[1]]$translations$translatedText
    aa <- strsplit(a, "\n\n\n")[[1]]
    aa <- gsub("@ +", "@", aa)
    aa <- gsub("^\n +", "", aa)
    aa <- aa[aa!=""]
    alltrans[[cand]][[i]] <- aa
    if (! i%%10) print(paste0("Candidate ", cand, ": ", i, " out of ", howmany))
clean <- function(t) {
  t <- gsub('[[:punct:]]', '', t)
  t <- gsub('[[:cntrl:]]', '', t) 
  t <- gsub('\\d+', '', t)
  t <- gsub('[[:digit:]]', '', t)
  t <- gsub('@\\w+', '', t)
  t <- gsub('http\\w+', '', t)
  t <- gsub("^\\s+|\\s+$", "", t)
  t <- gsub('"', '', t)
  t <- strsplit(t,"[ \t]+")
  t <- lapply(t, tolower)
alltrans2 <- lapply(alltrans, unlist)
alltrans3 <- lapply(alltrans2, clean)

As we see, this clean-up included removing punctuation, control characters, URLs, and digits from the tweets, and then splitting them at spaces or tabs. For matching, conversion to lowercase was used.

Analysing sentiments

First and foremost, let us look at the distributions of positive and negative tweet counts for various candidates.

positive <- scan('positive-words.txt', what='character', comment.char=';')
negative <- scan('negative-words.txt', what='character', comment.char=';')
posscore <- function(tweet) {
pos.match <- match(tweet, positive)
pos.match <- !is.na(pos.match)
pos.score <- sum(pos.match)
negscore <- function(tweet) {
neg.match <- match(tweet, negative)
neg.match <- !is.na(neg.match)
neg.score <- sum(neg.match)
posscores <- list()
negscores <- list()
for (i in 1:9) {
posscores[[i]] <- unlist(lapply(alltrans3[[i]], posscore))
negscores[[i]] <- unlist(lapply(alltrans3[[i]], negscore))
poscounts <- lapply(posscores, table)
negcounts <- lapply(negscores, table)
cols <- rainbow(10)
cairo_pdf("counts1.pdf", 7, 5)
plot(NULL, NULL, xlim=c(0, 6.7), ylim=c(0, 7516), main = "Positive tweet counts for candidates", ylab = "Tweets", xlab="Positive words in a tweet")
for (j in 1:9) {
for (i in 1:length(poscounts[[j]])) {
lines(c(i-1 + (j-1)/10, i-1 + (j-1)/10), c(0, poscounts[[j]][i]), lwd=5, col=cols[j])
legend("topright", finds, lwd=5, col=cols)
cairo_pdf("counts2.pdf", 7, 5)
plot(NULL, NULL, xlim=c(0, 6.7), ylim=c(0, 7516), main = "Negative tweet counts for candidates", ylab = "Tweets", xlab="Negative words in a tweet")
for (j in 1:9) {
for (i in 1:length(negcounts[[j]])) {
lines(c(i-1 + (j-1)/10, i-1 + (j-1)/10), c(0, negcounts[[j]][i]), lwd=5, col=cols[j])
legend("topright", finds, lwd=5, col=cols)

Distribution of positive word counts

Distribution of negative word counts

Fig. 1. Distribution of tweets

Since there is no real political competition to Putin (position 1) among the present candidates (positions 2–8), let us pay some attention to his closest political rival who was denied access to the elections, Navalny (position 9). As we can see from Fig. 1, the number of tweets related to Putin and containing 1–2 positive words is smaller than that related to Navalny. At the very same time, paradoxically, the number of tweets related to Putin and containing 1–2 negative words is also smaller than that of Navalny.

totpos <- numeric(9)
totneg <- numeric(9)
for (i in 1:9) {
totpos[i] <- sum(poscounts[[i]] * as.numeric(names(poscounts[[i]])))
totneg[i] <- sum(negcounts[[i]] * as.numeric(names(negcounts[[i]])))
# Ordering candidates not alpabetically but as they are in the database
a <- factor(finds)
finds <- factor(a, levels(a)[c(5, 1, 2, 3, 6, 7, 8, 9, 4)])
ratios <- totpos/totneg
ratiosdf <- data.frame(ratio=ratios, name=finds)
p <- ggplot(data=ratiosdf, aes(x=name, y=ratio, fill=name)) + geom_bar(stat="identity") + ylab("Positive/negative ratio") +
theme_minimal() + coord_flip() + scale_x_discrete(limits = rev(levels(ratiosdf$name))) + theme(legend.position="none", axis.title.y=element_blank())
cairo_pdf("ratios.pdf", 8, 7)

Ratio of positive to negative tweet counts

Fig. 2. Tweet sentiment ratios for candidates

It is unsurprising that that the ratio for Navalny, who is known as a fighter against corruption, is lower than that of Putin, despite the fact that there is a substantial number of opposing bloggers, due to the fact that the word “corruption” is negative per se. In general, only one candidate (Grudinin) has this ratio greater or equal to one. This means that tweets containing the names of political leaders are negative in tone in general.

Now it it time to see which words were the top positive and top negative for each candidate.

poswords <- function(tweets) {
pmatch <- match(t, positive)
posw <- positive[pmatch]
posw <- posw[!is.na(posw)]
negwords <- function(tweets) {
pmatch <- match(t, negative)
negw <- negative[pmatch]
negw <- negw[!is.na(negw)]
pdata <- list()
ndata <- list()
for (j in 1:9) {
pdata[[j]] <- ""
ndata[[j]] <- ""
for (t in alltrans3[[j]]) {
pdata[[j]] <- c(poswords(t), pdata[[j]])
ndata[[j]] <- c(negwords(t), ndata[[j]])
pfreqs <- lapply(pdata, table)
nfreqs <- lapply(ndata, table)
dpfreq <- list()
dnfreq <- list()
for (j in 1:9) {
thresh <- length(alltrans2[[j]])/200
a <- pfreqs[[j]]
a <- a[a>thresh]
b <- nfreqs[[j]]
b <- b[b>thresh]
dpfreq[[j]] <- data.frame(word=as.character(names(a)), freq=as.numeric(a))
dpfreq[[j]]$word <- as.character(dpfreq[[j]]$word)
dnfreq[[j]] <- data.frame(word=as.character(names(b)), freq=as.numeric(b))
dnfreq[[j]]$word <- as.character(dnfreq[[j]]$word)
for (j in 1:9) {
p1 <- ggplot(dpfreq[[j]], aes(word, freq)) + geom_bar(stat="identity", fill="lightblue") + theme_bw() +
geom_text(aes(word, freq, label=freq), size=4) + labs(x="Major Positive Words", y="Frequency of Occurence",
title=paste0("Major Positive Words and Occurence for \n", finds[j], ", n = ", length(alltrans2[[j]]))) + 
p2 <- ggplot(dnfreq[[j]], aes(word, freq)) + geom_bar(stat="identity", fill="pink") + theme_bw() +
geom_text(aes(word, freq, label=freq), size=4) + labs(x="Major Negative Words", y="Frequency of Occurence",
title=paste0("Major Negative Words and Occurence for \n", finds[j], ", n = ", length(alltrans2[[j]]))) + 
cairo_pdf(paste0("posw", j, ".pdf"),  2+nrow(dpfreq[[j]])/8, 5)
cairo_pdf(paste0("negw", j, ".pdf"),  2+nrow(dnfreq[[j]])/8, 5)

Positive words for Putin
Negative words for Putin

Positive words for Baburin
Negative words for Baburin

Positive words for Grudinin
Negative words for Grudinin

Positive words for Zhirinovsky
Negative words for Zhirinovsky

Positive words for Sobchak
Negative words for Sobchak

Positive words for Surajkin
Negative words for Surajkin

Positive words for Titov
Negative words for Titov

Positive words for Yavlinsky
Negative words for Yavlinsky

Positive words for Yavlinsky
Negative words for Navalny

Fig. 3. Most frequent positive and negative words for candidates

We defined “most frequent” words as words whose count exceeded the total number of tweets divided by 200. There is just one small problem: such generic words as “like” and “right”, “well” etc. are on this table. We can remedy that by manually constructing a table of most popular meaningful positive and negative words for candidates (Table 1).

Candidate 1st + word 2nd + word 1st − word 2nd − word
Putin support 275 popular 252 problems 224 protests 153
Baburin important 30 right 27 curses 340 shit 235
Grudinin interesting 416 respect 266 dirty 232 poor 160
Zhirinovsky benefit 225 entertain 206 curses 339 whore 333
Sobchak useful 165 truthful 149 whore 571 beg 410
Surajkin free 86 regard 61 provocation 348 curses 339
Titov works 51 ready 30 shit 284 scandal 237
Yavlinsky liberty 91 great 83 sorry 339 shit 294
Navalny top 232 good 181 strike 355 boycott 352

Table 1. Two most frequent meaningful words for candidates


We can make several conclusions. First, several candidates (Baburin, Surajkin, Titov, Yavlinsky) are so unpopular that they were not mentioned 10 000 times over the course of 2.5 months since the beginning of 2018, which implies that they were added to the list of approved candidates to create the illusion of choice; they cannot compete against the obvious leader of the race. Next, on average, people tweet about politicians when they are discontent with something; it is reflected in the average negative score of tweets, except for Putin and Grudinin. Some politicians (Zhirinovsky, Sobchak) are viewed as politically promiscuous, which is reflected in the word frequency analysis. This all creates the illusion of choice presence, whereas most of the population of Russia does not have access to Twitter, or are not politically engaged, or are dependent on the subsidies issued by the present government, or cannot fully explore the majority of opposing opinions because they are carefully filtered out of the central and official media.


Bessi, Alessandro and Emilio Ferrara (2016). ‘Social bots distort the 2016 US Presidential election online discussion’.

Bhatia, Aankur (2015). Twitter Sentiment Analysis Tutorial. Rpubs.

Burgess, Jean and Axel Bruns (2012). ‘(Not) the Twitter election: the dynamics of the #ausvotes conversation in relation to the Australian media ecology’. Journalism Practice 6.3, pp. 384–402.

Kapko, Matt (2016). Twitter’s impact on 2016 presidential election is unmistakable. CIO.

Larsson, Anders Olof and Hallvard Moe (2012). ‘Studying political microblogging: Twitter users in the 2010 Swedish election campaign’. New Media & Society 14.5, pp. 729–747.

Sang, Erik Tjong Kim and Johan Bos (2012). ‘Predicting the 2011 dutch senate election results with twitter’. Proceedings of the workshop on semantic analysis in social media. Association for Computational Linguistics, pp. 53–60.

Wang, Hao et al. (2012). ‘A system for real-time twitter sentiment analysis of 2012 us presidential election cycle’. Proceedings of the ACL 2012 System Demonstrations. Association for Computational Linguistics, pp. 115–120.

Yang, Xiao, Craig Macdonald and Iadh Ounis (2017). ‘Using word embeddings in twitter election classification’. Information Retrieval Journal, pp. 1–25.

Гибель России

Сто лет назад погибла Россия. Не могу собраться с мыслями, поэтому привожу отрывки идей, приходящих в голову.

Читал «Солнце мёртвых» Шмелёва — слёзы наворачиваются на глаза. Как пел Тальков: «О, генеральская тетрадь, забытой правды возрожденье, как тяжело тебя читать обманутому поколенью». Нет больше той самой России, которая подарила миру блестящих писателей и композиторов, которые сформировали то, что все называют русской культурой. Горько от этого.

Отмечать столетие революции — значит радоваться гибели родной культуры.

Да, у меня крестьянские корни, моими предками были малороссийские крестьяне, поэтому, живи я в Российской империи, наиболее ярким событием всей жизни была бы смерть в 30 лет от тифа. Тем не менее, лучше бы уж я сто раз умер в Российской империи крестьянином, чем один раз родился в современной России. Если Бога нет, то кого мне благодарить за то, что хотя бы не родился в СССР?

Если бы у меня была возможность вызвать дух неизвестного белогвардейца и высказать ему все свои мысли, то я бы произнёс всего лишь два слова: «не уберегли».

А современный русский интеллигент мечтает сделать две вещи: устроить в России революцию и бежать во Францию.

О коммунистах

Во «Власти Народа» передовая: «Настал грозный час — гибнет Россия и Революция. Все на защиту революции, так ещё недавно лучезарно сиявшей миру!» — Когда она сияла, глаза ваши бесстыжие?

Ив. Бунин, «Окаянные дни».

Среди людей интеллигентных не принято высказываться о политике — заведено вежливо молчать. С другой стороны, во-первых, ваш покорный слуга никогда не претендовал на интеллигентность, а во-вторых, если все будут молчать (из врождённой незлобливости или от блестящего дворянского воспитания), то в таком случае, как сказал великий, «мы окрасим себя в те цвета, в которые мы окрасим себя» — будем иметь что имеем.

Сегодня получил весточку из России, однако, как оказалось, не самую приятную. КПРФ распространяет по почтовым ящикам листовки, в которых призывает голосовать за своих кандидатов в муниципальные депутаты в Москве.

Я не удивлён, что в политику лезет всякая сволота. Если кто-то задавался вопросом, почему российская экономика так слаба и неконкурентоспособна на международной арене, ответ лежит прямо у него в почтовом ящике. Кумачовые цареубийцы и сермяжные леворуционеры. Почему агитируют они, а стыдно мне? Как у них вообще хватает наглости в столетнюю годовщину великой русской катастрофы и гибели не только русского государства, но и многовековой русской культуры проповедовать коммунизм и ещё пытаться на нём нажиться?

St petersburg demonstration revolution

Однако по прочтении их предвыборной программы в мою душу закрались сомнения. Если в планах кандидатов не значится разжигать пожар мировой революции, то что это за коммунисты такие? Какое-то жалкое недоразумение, предатели собственной идеологии. Хороший коммунист — мёртвый коммунист!

О вреде дробления выборки

Предположим, изначально у нас было одно полное облако точек. Мы разделили его на три непересекающихся подмножества (обозначены цветами). В каждом из цветных облаков есть значимая взаимосвязь между переменными \(X\) и \(Y\), которую обнаруживают любые регрессионные методы (приведены три: классический МНК, квантильная регрессия при \(q=0{,}5\) и локально линейная регрессия первой степени).

Ложные значимые эффекты на подвыборках

Однако если взглянуть на изначальное облако из всех точек всех трёх цветов, то эффекта никакого не будет (эта ничтожно слабая и малозначимая зависимость показана толстой чёрной линией). Получается парадокс: если индивид относится к зелёной подвыборке, то в ней влияние \(X\) на \(Y\) есть. То же верно и для всех остальных подвыборок. Везде эффект положительный! Однако одновременно для всех точек никакого эффекта нет.

Зависимая переменная: Y
Вся выборка Синие Зелёные Красные
X 0.013 0.839*** 0.482*** 0.598***
(0.030) (0.024) (0.048) (0.046)
Константа 0.004 0.013 -1.202*** 1.245***
(0.031) (0.019) (0.055) (0.053)
Наблюдений 1000 386 307 307
R2 0.0002 0.756 0.252 0.361
Adjusted R2 -0.001 0.755 0.250 0.359
Residual Std. Error 0.981 (df = 998) 0.373 (df = 384) 0.667 (df = 305) 0.640 (df = 305)
F Statistic 0.198 (df = 1; 998) 1,187.609*** (df = 1; 384) 102.762*** (df = 1; 305) 172.266*** (df = 1; 305)
Note: *p<0.1; **p<0.05; ***p<0.01

Вывод: чем более избирательно исследователь будет составлять выборку для исследования («пожилое коренное население, которое до этого трудилось на работах, не требующих высокой квалификации»), тем больше вероятность, что он что-нибудь да обнаружит... и что эта находка будет ложной.

Код для репликации в R (отчего-то плагин глючит и склеивает всё в строку):

n <- 1000; set.seed(100); x <- rnorm(n); y <- rnorm(n); th <- 0.7; g1 <- (y < x + th) & (y > x - th);
g2 <- (y <= x - th); g3 <- (y >= x + th);
m <- lm(y~x); m1 <- lm(y~x, subset=g1); m2 <- lm(y~x, subset=g2); m3 <- lm(y~x, subset=g3)

Самое кошмарное музыкальное произведение

В Сети есть страница с очень интересным списком произведений, озаглавленная «The Darker Side of Classical Music» («Тёмная сторона классической музыки»). На ней собраны образцы наиболее трагичных произведений, которые вышибают у слушателей слезу или вселяют в них ужас. Некоторые записи в нём спорны (Шостакович?), некоторые не вызывают никакого сомнения (Шестая симфония Чайковского, «Плач по жертвам Хиросимы» Пендерецкого, «Остров мёртвых» Рахманинова). Как и в любом подобном списке, в нём есть фамилии забытых позднеромантических композиторов второго эшелона.

Однако одной записи в нём не хватает. Не хватает упоминания композитора, известного как «Чёрный Балакирев» благодаря разрушительной и мрачной силе, присутствующей в его произведениях. Это Сергей Михайлович Ляпунов, родной брат Александра Ляпунова. Он является автором двух симфоний и двух фортепианных концертов. Каждый из них играет тысячами разных красок: Первый концерт — классическая русская печаль, Второй концерт — новь, свежее дыхание, короткий, но изящный эксперимент с гармонией, Первая симфония — эпическое произведение, весь финал которого представляет собой пиррову победу, радость со слезами на глазах...

Однако у Ляпунова есть одно произведение, о котором почти никто не знает. Его почти никогда не исполняют. Во всём зарубежном интернете нет ни одной статьи, посвящённой ему. Это Вторая симфония — самая острая музыкальная катастрофа, чёрный кошмар, падение в пропасть безумия, олицетворение демона самоубийства и символ гибели России. Написанное в 1917 году, оно содержит максимальную концентрацию трагических чувств в первой части. Если у Скрябина первая часть Второй симфонии — это непрерывная борьба с Природой, напряжённая и предвещающая грозу, то у Ляпунова намного больше личного трагизма: мировая война, революция (после которой композитор эмигрировал в Париж), нежелание принять крах великой империи, приходящейся ему родной страной... Всегда бывший мрачным и угнетающим, во Второй симфонии композитор зашёл за грань разрушительного и разбивающего сердце.

Сегодня исполнился ровно год с того самого момента, как в библиотеке Cité Universitaire была совершена самая катастрофическая ошибка 2015 года — была открыта, прослушана и переслушана симфония Ляпунова №2 си-бимоль минор. Именно 18 апреля все демоны, роившиеся внутри этого сундука, вырвались на свободу. Автор убедительно просит неподготовленного читателя смириться с тем, что полчище ночных бесов будет подталкивает прослушивающего эту симфонию сброситься с моста, вспороть живот, взрезать горло или что-нибудь похуже. Все, кто не боится перейти на чёрную сторону искусства, приглашаются к прослушиванию этой музыкальной гибели целой страны только в высококачественных наушниках или перед полноценной акустической системой. Помощи вам ждать неоткуда, никто к вам не придёт. Если вдруг вы не сможете остановиться, заставьте кого-нибудь заставьте вас поклясться самому/самой себе, что никогда в жизни вы больше не переслушаете этого произведения.

Экспонента Ляпунова / Exposant de Liapounov

У композитора Ляпунова произведения настолько мрачные и сокрушающие, что экспонента Ляпунова отрицательная, но хаос при этом растёт!

La musique de compositeur Liapounov est si sombre et écrasante que son exposant est négatif mais son chaos s’accroît!

P.S. Прошу кого-нибудь перевести эту фразу на немецкий, дабы мы могли узреть все четыре варианта написания (включая «Ljapunow») в одной записи.

«Школьная» задача про возраст членов семьи

Три версии одной и той же задачки. Числа и формулировки немного разные, ответ одинаковый.

  • Вася младше своей мамы на 21 год. 15 лет назад отношение возраста Васи к разнице их с мамой возрастов было меньше возраста мамы в то время ровно в 9 раз. Вопрос: где сейчас Васина бабушка?
  • Вася младше своей мамы на 28 лет. 8 лет назад отношение возраста Васи к разнице их с мамой возрастов составляло ровно 15 % возраста мамы в то время. Вопрос: где сейчас Васин дедушка?
  • Вася младше своей мамы на 24 года. 18 лет назад отношение возраста Васи к разнице их с мамой возрастов составляло ровно 9,5 % возраста мамы в то время. Вопрос: где сейчас Васина бабушка?