1. Code Library

In [1]:
HTML("""<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: gainsboro;} 
a {color: seagreen; font-family: 'Roboto';} 
h1 {color: slategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;} 
h2, h3 {color: darkslategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #aaa;}
h4 {color: slategray; font-family: 'Roboto';}
span {text-shadow: 4px 4px 4px #ddd;}
div.output_prompt, div.output_area pre {color: darkslategray;}
div.input_prompt {color: seagreen;} 
div.output_stderr pre {background-color: ghostwhite;}  
div.output_stderr {background-color: gainsboro;}
</style>""")
Out[1]:
In [ ]:
# jupyter notebook --NotebookApp.iopub_data_rate_limit=2147483647
In [43]:
Pkg.resolve()
INFO: No packages to install, update or remove
In [110]:
# Pkg.clone("http://github.com/cormullion/Astro.jl")
In [7]:
using PyCall, PyPlot
using SymPy, LaTeXStrings
using DataFrames, RDatasets
In [15]:
using GR, Plotly
using Interact, Plots
using Winston, Astro
In [9]:
using UnicodePlots
using Distributions, QuantEcon
WARNING: using QuantEcon.update! in module Main conflicts with an existing identifier.
In [10]:
using GLVisualize, Colors 
using GeometryTypes, Reactive
In [14]:
# init_notebook(true)

2. Data

In [16]:
days = DateTime(2016,1,1,0,0,0):DateTime(2016,12,31,0,0,0);
eq_values=Float64[equation_time(Dates.datetime2julian(day)) for day in days];
In [17]:
head(RDatasets.datasets(), 20)
Out[17]:
PackageDatasetTitleRowsColumns
1COUNTaffairsaffairs60118
2COUNTazdrg112azdrg11217984
3COUNTazproazpro35896
4COUNTbadhealthbadhealth11273
5COUNTfasttrakgfasttrakg159
6COUNTlbwlbw18910
7COUNTlbwgrplbwgrp67
8COUNTloomisloomis41011
9COUNTmdvismdvis222713
10COUNTmedparmedpar149510
11COUNTrwmrwm273264
12COUNTrwm5yrrwm5yr1960917
13COUNTshipsships407
14COUNTtitanictitanic13164
15COUNTtitanicgrptitanicgrp125
16EcdatAccidentShip Accidents405
17EcdatAirlineCost for U.S. Airlines906
18EcdatAirqAir Quality for Californian Metropolitan Areas306
19EcdatBenefitsUnemployement of Blue Collar Workers487718
20EcdatBidsBids Received By U.S. Firms12612
In [18]:
titanic = dataset("datasets","titanic")
head(titanic, 10)
Out[18]:
ClassSexAgeSurvivedFreq
11stMaleChildNo0
22ndMaleChildNo0
33rdMaleChildNo35
4CrewMaleChildNo0
51stFemaleChildNo0
62ndFemaleChildNo0
73rdFemaleChildNo17
8CrewFemaleChildNo0
91stMaleAdultNo118
102ndMaleAdultNo154
In [51]:
x = [1.2,3.5,5.8,8.2,10.5,12.2,15.6,17.3,18.9,20.1]
y = [0.8 2.1 4.2 5.7 6.5 7.9 9.6 11.3 15.6 19.9]

x1, y1, z1 = [1,3,5], [0,0,0], [0,0,0]
dx1, dy1, dz1 = [1, 1, 1], [3, 3, 3], [5, 3, 7]

x2 = [2,3,4]
y2 = [1,3,5]
z2 = [[2,1,1], [3,3,8], [4,5,5]]

numbers = rand(10,4)
equation(numbers) = -5 * tan.(numbers) + 10 * tan.(3*numbers + 100);
In [20]:
Θ = linspace(0,6π,200)
Out[20]:
0.0:0.09472138654039577:18.84955592153876
In [21]:
writedlm("test.txt", numbers)
numbers = readdlm("test.txt")
Out[21]:
10×4 Array{Float64,2}:
 0.590219  0.943898    0.561009   0.587788
 0.739152  0.329717    0.636248   0.182163
 0.114208  0.426526    0.446581   0.849524
 0.429684  0.21357     0.989926   0.828256
 0.58559   0.680537    0.0738746  0.352194
 0.863448  0.0348192   0.523325   0.418635
 0.160806  0.35391     0.429863   0.405065
 0.193606  0.0699052   0.772781   0.905598
 0.745369  0.879685    0.891181   0.367331
 0.1954    0.00263321  0.133717   0.682798
In [22]:
vectors = ([-3, 2], [4, 3], [1, 5])
x_array = zeros(2, length(vectors))
y_array = zeros(2, length(vectors));
In [23]:
labels = []
for l = 1:length(vectors)
    vector_label = vectors[l]
    x_array[2, l] = vector_label[1]
    y_array[2, l] = vector_label[2]
 
    labels = [labels; (1.1 * vector_label[1], 1.1 * vector_label[2], "$vector_label")]
end
In [24]:
labels
Out[24]:
3-element Array{Any,1}:
 (-3.3, 2.2, "[-3, 2]")
 (4.4, 3.3, "[4, 3]")  
 (1.1, 5.5, "[1, 5]")  

3. Maths

In [30]:
@vars a b c
Out[30]:
(a, b, c)
In [26]:
p=expand( (a+1)*(a-2)*(a^2-10) )
Out[26]:
a^4 - a^3 - 12*a^2 + 10*a + 20
In [27]:
factor(p)
Out[27]:
(a - 2)*(a + 1)*(a^2 - 10)
In [28]:
polyroots(p)
Out[28]:
\begin{equation*}\begin{cases}-1 & \text{=>} &1\\\sqrt{10} & \text{=>} &1\\- \sqrt{10} & \text{=>} &1\\2 & \text{=>} &1\\\end{cases}\end{equation*}
In [29]:
map(N,SymPy.solve(p))
Out[29]:
4-element Array{Real,1}:
 -1      
  2      
 -3.16228
  3.16228

4. Plotting

4.1 PyPlot

In [16]:
fig1 = PyPlot.figure(figsize=(14,7))
surf(randn(20,20), cmap="bone", alpha=0.4);
In [13]:
bar3D(x1, y1, z1, dx1, dy1, dz1);
In [15]:
fig2 = PyPlot.figure(figsize=(14,7))
contour3D(x2, y2, z2, extend3d=true, stride=1, cmap="bone", alpha=0.5, w=3);
In [17]:
scatter3D(rand(10,10), rand(10,10), rand(10,10), marker="8", c="darkgreen", alpha=0.5);
In [19]:
fig3 = PyPlot.figure(figsize=(14,7))
csd(rand(100,100), rand(100,100), color="darkgreen")
Out[19]:
(Complex{Float64}[1.90566+0.0im, 3.01945-0.0542843im, 1.53577-0.080629im, 0.621069-0.0909297im, 0.327349-0.0899964im, 0.169487-0.0649538im, 0.0450298-0.026562im, 0.0221473+0.00084193im, 0.0545346+0.00785824im, 0.0675704-0.00195949im  …  -0.0037811+0.00632724im, -0.00775205+0.00946474im, -0.0134511+0.00758717im, -0.0170313-0.00333804im, -0.0142283-0.01454im, -0.00518421-0.0180279im, 0.00439145-0.0180793im, 0.00535586-0.0186078im, -0.00369443-0.0136956im, -0.00493465+0.0im], [0.0, 0.0078125, 0.015625, 0.0234375, 0.03125, 0.0390625, 0.046875, 0.0546875, 0.0625, 0.0703125  …  0.929688, 0.9375, 0.945313, 0.953125, 0.960938, 0.96875, 0.976563, 0.984375, 0.992188, 1.0])

4.2 Plots

In [54]:
gr()
Out[54]:
Plots.GRBackend()
In [71]:
Plots.plot(p, -4, 4, label="function (a+1) * (a-2) * (a^2-10)", size=(900, 400), w=2)
Out[71]:
-3 -2 -1 0 1 2 3 0 30 60 90 function (a+1) * (a-2) * (a^2-10)
In [72]:
Plots.plot([sin,cos], -5pi, 5pi, label=["sin","cos"], w=3, size=(900, 400))
Out[72]:
-15 -10 -5 0 5 10 15 -0.75 -0.50 -0.25 0.00 0.25 0.50 0.75 sin cos
In [112]:
Plots.plot(eq_values, size=(900, 400), line=(2,:dash), label="line")
Out[112]:
50 100 150 200 250 300 350 -10 -5 0 5 10 15 line
In [113]:
pyplot()
Out[113]:
Plots.PyPlotBackend()
In [114]:
Plots.plot(x_array, y_array, arrow=true, color=:blue, size=(700, 500),
           legend=:none, xlims=(-5, 5), ylims=(-1, 7), title="Vector Addition",
           annotations = labels, xticks=-5:1:5, yticks=-1:1:7)
vline!([0], color=:black)
hline!([0], color=:black)
Out[114]:
In [124]:
Plots.plot(equation(numbers), xlims=(1, 10), ylims=(-450, 150), size=(900, 400))
Out[124]:
In [132]:
z = rand(20,3)
Plots.plot(z,xaxis=("XLABEL",(-5,30),0:2:20,:flip),yaxis=("YLABEL",:log10),
           background_color=RGB(0.4,0.4,0.4),
           leg=false,title="TITLE",size=(1250, 450))
hline!(mean(z,1) + rand(1,3),line=(2,:dash,0.7,[:lightblue :royalblue :blue]))
vline!([5,10,15], line=(2, :dash))
Out[132]:
In [45]:
Plots.scatter(rand(100), rand(100), leg=false,
              ms=20*rand(100), alpha=0.5, c=:darkgreen,
              xlims=(-0.1, 1.1), ylims=(-0.1, 1.1), size=(900, 400))
Out[45]:
In [39]:
plotly()
Out[39]:
Plots.PlotlyBackend()
In [49]:
Plots.plot(Θ,abs.(0.1 * randn(200) + sin.(3Θ)),proj=:polar, size=(900, 400), label="sin")
Plots.plot!(Θ,abs.(0.1 * randn(200) + cos.(3Θ)),proj=:polar, label="cos")
Out[49]:
In [52]:
Plots.plot(x, numbers, title="Title", label=["First Line" "Second Line" "Third Line" "Fourth Line"], size=(900, 400))
Out[52]:
In [53]:
start = Date(2015, 6, 21)
x4 = map(d -> start + Base.Dates.Day(d), 1:120)
y4 = 15 + randn(120) * 4
Plots.plot(x4, y4, title="A typical British Summer",size=(900, 400), label="temperature")
Out[53]:
In [54]:
unicodeplots()
Out[54]:
Plots.UnicodePlotsBackend()
In [ ]:
Plots.plot(Vector[randn(100),randn(100) * 100],axis=[:l :r],ylabel="LEFT",yrightlabel="RIGHT")
In [ ]:
Plots.histogram(randn(1000),nbins=50)

4.3 UnicodePlots

In [146]:
mplt=lineplot([-1, 2, 3, 7], [1, 2, 9, 4], title = "Unicode Plot", name = "first line", canvas = AsciiCanvas, 
              border = :ascii, color=:blue, width = 90)
lineplot!(mplt, [0, 4, 8, 10], [10, 1, 10, 1], color = :yellow, name = "second line")
Out[146]:
                                            Unicode Plot
     +------------------------------------------------------------------------------------------+            
   9 |           ,    "-.                         /"\-._                                        | first line 
     |           |      "\..                     .`     "\-_.                                   | second line
     |           |         '`.                  .`          ""`-_.                            .f|            
     |           |            "-.              .`                ""-._.                    .r/` |            
     |           |              "\..          ./                      '"-._              ./`    |            
     |           |                 '`.        /                            "\-._      .-"       |            
     |           |                    "-.    /                                  "\-.,/`         |            
     |           |                      "\../                                    ./`""`-_.      |            
     |           |                         )`.                                .-"        ""`._. |            
     |           |                        .`  "-.                          .r/`               '\|            
     |           |                       .`     "\..                     ./`                    |            
     |           |                      ./         '`.                .-"                       |            
     |           |                      /             "-.          .r/`                         |            
     |           |      ______------""""                "\..     ./`                            |            
   1 |______-----r""""""                                   '`._-"                               |            
     +------------------------------------------------------------------------------------------+            
     -1                                                                                         7
In [147]:
mplt2=densityplot(randn(1000), randn(1000), color = :blue, width = 90)
densityplot!(mplt2, randn(1000) + 1, randn(1000) + 2, color = :red)
Out[147]:
      ┌──────────────────────────────────────────────────────────────────────────────────────────┐ 
    4                                                                                        
                                                                               
                                                                        
                                                                
                                                              
                                                            
                                                              
                                                           
                                                                   
                                                                             
                                                                                          
                                                                                                
                                                                                                
                                                                                                
   -4                                                                                           
      └──────────────────────────────────────────────────────────────────────────────────────────┘ 
      -4                                                                                         4

4.4 Other Packages

In [35]:
# Winston
Winston.plot(x, y, "g*")
Out[35]:

5. Animations

In [36]:
pyplot()
Out[36]:
Plots.PyPlotBackend()
In [37]:
p1 = Plots.plot([sin,cos], zeros(0), leg=false, size=(900, 400));
anim1 = Animation();
for t = linspace(0,20π,200)
    push!(p1,t,Float64[sin(t),cos(t)])
    frame(anim1)
end;
gif(anim1, "anim1.gif", fps=15)
INFO: Saved animation to /Users/olgabelitskaya/reflections2/anim1.gif
Out[37]:
In [38]:
n = 1500
dt = 0.02
σ, ρ, β = 10., 28., 8/3
x, y, z = 1., 1., 1.

# initialize a 3D plot with 1 empty series
p2 = path3d(1, xlim=(-25,25), ylim=(-25,25), zlim=(0,50),
            xlab = "x", ylab = "y", zlab = "z", label="line",
            title = "Lorenz Attractor", marker = 1, size=(900, 700))

# build an animated gif, saving every 10th frame
@gif for i=1:n
    dx = σ*(y - x)     ; x += dt * dx
    dy = x*(ρ - z) - y ; y += dt * dy
    dz = x*y - β*z     ; z += dt * dz
    push!(p2, x, y, z)
end every 10
INFO: Saved animation to /Users/olgabelitskaya/reflections2/tmp.gif
Out[38]:

6. Interactions

In [40]:
togglebutton(label="push"; value=true)
Out[40]:
In [41]:
dropdown(["one", "two", "three"])
Out[41]:

7. Quantitative Economics

In [42]:
P1 = [0.33 0.33 0.34; 0.1 0.8 0.1; 0.33 0.33 0.34]; MC1 = MarkovChain(P1)
Out[42]:
Discrete Markov Chain
stochastic matrix of type Array{Float64,2}:
[0.33 0.33 0.34; 0.1 0.8 0.1; 0.33 0.33 0.34]
In [43]:
X1 = simulate(MC1, 100000); mean(X1 .== 1)
Out[43]:
0.18714