Tuesday, June 5, 2012

First Attempt at Modeling Crime in Chicago

In my last post, I showed how to use the Socrata Open Data API (SODA) to download the data of the crimes reported in Chicago, how to plot the locations, and how to count the number of crimes that occurred in a certain area. This post will chronicle my first attempts to model that data in Mathematica.

The time series analysis add-on to Mathematica 8 costs about $295. So I've decided to write my own autoregressive model (AR) package as a start to modeling the crimes in Chicago. My AR code in Mathematica is based off the FitAR R-package and its associated paper. The mathematics and derivations of autoregressive models are already heavily covered on other websites, so I will not be explaining it here. The alpha version of my code can be found here, note it is not complete and does not yet have all the functions of FitAR or the Mathematica time series add-on.

My code, at this point, does provide fits that are comparable to the FitAR package. Using the default "lynx" data in R the following fits and associated residual autocorrelation plots were produced:


Mathematica

AR(1) Fit
MLEsdZ-ratio
phi(1)0.717290.065258910.9914
mu1537.94364.4774.21957





AR(4) Fit
MLEsdZ-ratio
phi(1)1.124280.090587412.411
phi(2)-0.7166670.136707-5.24237
phi(3)0.2626610.1367071.92135
phi(4)-0.2539830.0905874-2.80374
mu1537.94135.75511.3288






Subset AR(1,2,4,5,7,10,11) Fit
MLEsdZ-ratio
phi(1)0.8204550.017864945.9256
phi(2)-0.6328180.0972914-6.50436
phi(4)-0.1419510.0684639-2.07337
phi(5)0.1418930.07481931.89647
phi(7)0.2020380.09928762.03488
phi(10)-0.3141050.0917768-3.42249
phi(11)-0.3686580.0870617-4.23444
mu6.685910.10065766.4225

R

AR(1) Fit
MLEsdZ-ratio
phi(1)0.7173030.065257710.9918
mu1538.02363.9864.22548





AR(4) Fit
MLEsdZ-ratio
phi(1)1.124630.090580312.4158
phi(2)-0.7173960.1367150-5.24738
phi(3)0.2633550.1367151.92630
phi(4)-0.2542730.0905803-2.80716
mu1538.02135.46911.3533






Subset AR(1,2,4,5,7,10,11) Fit
MLEsdZ-ratio
phi(1)0.82044900.0178600545.937651
phi(2)-0.63284330.09731087-6.503316
phi(4)-0.14208880.06847123-2.075161
phi(5)0.14213880.074814091.899894
phi(7)0.20212500.099273762.036036
phi(10)-0.31409540.09178210-3.422186
phi(11)-0.36865890.08706171-4.234455
mu6.68593290.0999920766.864631



Now that I know my code is correct, the next step will be figuring out if an autoregressive model can properly describe the crime data from Chicago. The lynx data from above is almost trivial when compared to the chaotic mess of crime data.

Time Series Plot of lynx data

Plot of daily totals of crimes in Chicago.

Just for fun, this is the residual autocorrelation of an AR(5) regressed with the crime series data from above:


Not a model anyone should ever depend on. The files used in this post can be found here.

Monday, May 7, 2012

Chicago Crime - Updated

I was a bit dismayed to discover that the EveryBlock API stopped working. One of my most popular posts, Chicago Crime, depended on this API heavily.

Here I present an alternative data source for my previous post and a fun update. The update is a quick and dirty method to create popular crime density plots, as shown below.


In the spirit of transparency, the city of Chicago has taken the initiative to electronically release a great deal of data with Socrata Open Data API (SODA). Luckily for us, this release includes all filed police reports. The records available through this API range from the year 2001 to the present, which dwarfs the two week range provided by EveryBlock's API. However, I would not recommend downloading all of this data as the text file is approximately 2GB in size.

In this post I use only the filed police reports from one year prior to present. The data is available in both JSON and CSV format. I only use the CSV format here for the convenience of those with an earlier version of Mathematica. To import this data into Mathematica:





A plot of all reported crimes in Chicago between February 1st and March 31st of 2012 was created with the data.


Plot of incidents for any period within the year can be easily created with the following Mathematica code. Restrict the data to the range of interest by replacing the dates of the start and end strings. Dates must be in the format of mm/dd/yyyy. This code simply finds the positions of the strings that match the inputed dates and plots the daily totals of incidents.










The data can be parsed into primary descriptions including arson, homicide, sex offense, weapons violation, crim sexual assault, interfere with public officer, gambling, public peace violation, criminal trespass, liquor law violation, assault, deceptive practice, burglary, criminal damage, robbery, motor vehicle theft, offense involving children, narcotics, theft, other offense, and battery. Below is the plot and code to filter for only narcotics incidents.






















A secondary description can also be used to parse the data. Some secondary descriptions include aggravated: handgun, poss: crack, armed: handgun, harassment by telephone, poss: heroin(white), to land, retail theft, unlawful entry, strongarm - no weapon, to property, poss: cannabis 30gms or less, from building, $500 and under, forcible entry, to vehicle, domestic battery simple, simple, automobile, over $500, telephone threat, and wireroom/sports. Below is the plot and code to filter for incidents with a primary description of narcotics and a secondary description of poss: cannabis 30gms or less.























The incidents may also be separated into ones where arrests were made and ones where no arrests were made. Below is code to filter for incidents with a primary description of narcotics and a secondary description of poss: cannabis 30gms or less with arrests and without. Both plots comparing to total narcotics incidents are shown.





















The method to display where certain incidents occur in chicago is similar to my previous post, Chicago Crime. Please refer to that posting for a more detailed explanation on how to create the plot below. The plot here is a geographical visualization of where arrests occurred relating to incidents of narcotics with possession of cannabis with 30 grams or less.


The method to tabulate the number of incidents within neighborhoods is also similar to my previous post, Chicago Crime. This calculation totals the numbers of incidents within each neighborhood boundary. It is the most costly in computational time and power because of the generality in the counting code that allows it to use any boundaries (such as census tracts, police beats, etc.) The tabulation of arrests made relating to incidents of narcotics with possession of cannabis with 30 grams or less in each neighborhood is presented.


While doing some initial research for this post, I found "crime hotspots" as a popular visualization option. A similar visualization is easily created in mathematica with three simple lines of code.













The Mathematica code used in this post can be downloaded here. Some fun analysis of crimes in chicago will follow in future posts.

Thursday, April 19, 2012

Can I Trust Wikipedia?

A question as dreaded as "Who's on first?" And one that I am forced to ask as I feel lucky often. One quick and fun way to address how much you can trust a wikipedia article is by looking at what else a contributor edits. This can easily be done through the magic of the MediaWiki API and Mathematica. Here is the result, with a CNN inspired example, of Mitt Romney's wikipedia article from April 19th, 2012.

The top 20 contributors to the Mitt Romney wikipedia article are highlighted in yellow and common articles edited by these contributors are highlighted in blue.

Personally, I see red flags when contributors of the Mitt Romney article are also subject-matter experts of Katy Perry, Springfield (The Simpsons), and Savage Love. I wouldn't put too much faith in its accuracy.

A copy of the notebook can be downloaded here. To use it, simply copy the title of the wikipedia article of interest and paste it into the third line. More to come the next time I skip lunch!

Saturday, November 26, 2011

Making Sense of Census-less Data

I have always found that supplemental 3D visualizations help provide better insights on census data. While playing with the compiled data from the 2000 census, from cityofchicago.org, I found an interesting anomaly.


After some investigation, I found the red spike represents 15 families with a median income of $255,000. Was there mischief afoot by those 15 families?

I'll let the more curious readers decide. Attached here is the census data and a Mathematica notebook. The notebook has been generalized to allow users to create 3D visualizations of all provided census data.

Download here

Thursday, November 10, 2011

Batman Letterhead in ScribTeX

As soon as I made my last post, I got a few emails asking how to use LaTeX to create the Batman letterhead.


Through the magic of "the cloud," there is an easy way to play with the letterhead I created without downloading LaTeX. First, download the source file, here.

There is a great website called ScribTeX that allows the compilation of TeX files through the website. Signing up is painless and free. Once you have signed up and logged on, you will see the Dashboard page. Click on New Project and you will be asked to name the new project. I chose the name "Batman Letterhead."


Then upload the TeX file containing the letterhead.


For the TeX file to compile properly, you must change the compiler to latex from ScribTeX's default pdflatex compiler. The pdflatex compiler compiles directly to a pdf. The latex compiler will create a postscript file before creating a pdf. The packages used to plot the Batman logo (pstricks and pst-plot) only make sense to postscript files and cannot be used with pdflatex. To change the compiler, click on "Settings" from the project page then the "Compiler Settings" tab.  After choosing latex, click "Save" then "Files."


Now open the uploaded TeX file and you will see that it is the same file as my previous post with one major difference. Instead of using a separate file containing the data points, this one has the data points stored within.


To compile the letterhead, click "Compile" and a new window will open with the compiled PDF.


The TeX file used in this post can be found here. Enjoy TeXing as Batman!

Batman Letterhead

After reading a post from HardOCP that gave the roots of the Batman symbol, I could not help imagining the letterhead of the world's greatest detective. The letterhead needs to say "Batman is classy."


I created this letterhead using the "Batman equation", Mathematica, and LaTeX. The computer in the Bat Cave is probably Unix-based and cannot use Microsoft Word. Therefore, Batman must use LaTeX. The first step to creating this letterhead is to plot the symbol. A post from Playing With Mathematica has done this for me already with seven simple lines.


The Show function is used to overlay the six plots to reveal the desired product.


To extract the points used for the final plot the following command must be executed for each root equation.




After extracting and compiling all data points into one .dat file, we are ready to create the letterhead in LaTeX. The following LaTeX code relies on the pstricks and pst-plot packages. It plots the points in the saved data file and creates the bar that separates Batman's contact information.

\begin{document}
\readdata{\BatData}{BatData.dat}
\noindent\begin{minipage}[b]{5cm}
\begin{center}
\psset{xunit=0.35cm,yunit=0.5cm}
\begin{pspicture}(0,0)(0,2)
\listplot[plotstyle=dots]{\BatData}
\end{pspicture}
\end{center}
\end{minipage}
\hfill
\begin{minipage}[b]{7cm}
\begin{flushright}
\footnotesize{\itshape 1007 Mountain Drive {\scriptsize$\bullet$} Gotham City, NY 10027}
\end{flushright}
\end{minipage}
\vskip-2mm
{\hspace{40mm}\hfill\rule[0.5mm]{130mm}{0.5pt}}
\vskip-2mm
\hfill
\begin{minipage}[b]{7cm}
\begin{flushright}
\footnotesize{\itshape 555.555.5555 {\scriptsize$\bullet$} \href{mailto:Bruce@WayneCorp.com}{Bruce@WayneCorp.com}}
\end{flushright}
\end{minipage}

All of the files discussed in this post can be downloaded here, along with a letter Batman would've sent to The Joker.

Tuesday, November 8, 2011

Google Insight Data to Predict Stock Market Trends, Part 1

Previously, I have demonstrated how to install pythonika and why weekends need to be considered in analyzing market trends.  Here I will share my code on importing Google Insights data into Mathematica and provide a neat example of how to parse and analyze the data.

To get started, please install pythonika and download my sample notebook.  Change the first line to point to your compiled executable of pythonika.




Then replace "USERNAME" and "PASSWORD" in the following line with your google account.







Evaluating the python cell, will download the daily search data of "AAPL" in the last 90 days.  To limit the search to the last 30 days, the date variable must be set to "today 01-m."  An important note, any data beyond 90 days are averaged over a week and will need to be parsed in a manner different from the example here.

This command will parse the CSV data for the dates and total daily searches:



Since I am interested in the financials of Apple (AAPL), specifically its daily traded volume, I have set :




The variables googstartdate and googenddate are automatically set to the date range indicated in the first cell.  The next part of the code is used to pair up trading dates with query dates, filter out the weekends, and remove lines with missing data.

There may be a more efficient method of matching two lists of unmatched lengths in Mathematica, but this was the first one I thought up that could account for holidays. Essentially, I have created a set of {dates, queries} and another set of {dates, stock volume} and must match the dates up to create one set of {dates, queries, stock volume}.  First I joined the lists together, then I reordered the two lists by:




The new set will contain disparities from weekends and possibly blank results from the Google Insight data.  To filter out these disparities from the new set, this command is applied:



A quick plot of the filtered data and unfiltered data will show if weekends were properly filtered out.

Unfiltered for weekends data

Filtered for weekends data

There have been a few papers that prove query volumes can be used to predict trading volumes.  But anyone can clearly see this is not the case with Apple.  This observation can be quantified with a direct Granger Causality test.  I have provided the code necessary to perform the test, but I leave it to the reader to test the lag sensitivity and establish the causal relation or feedback.  I will explain the code used for the Granger Causality test.

To create a new set in the form of {ylag1, ylag2, ylag3, xlag1, xlag2, xlag3, y} with a max lag of 3:





Then to perform the OLS regression and sum the squared residuals:






To compute the test statistic:




And since xlag = ylag, we only need to compute one f-test to get the corresponding p-value by:




The Mathematica notebook for this post can be downloaded here.

Monday, November 7, 2011

Installing Pythonika

Pythonika enables Mathematica to run python.  I ran into some problems installing it with Mathematica 8 and Lion 10.7.2 OS X from the official pythonika webpage.  Here are some quick tips for those performing a similar install.

  • download my appended version, here
  • install 64-bit Python 2.7.1, here 
  • soft link mathlink.framework inside the Mathematica application into the /Library/Frameworks directory using this command in the terminal
    • ln -s /Applications/Mathematica.app/SystemFiles/Links/MathLink/DeveloperKit//CompilerAdditions/mathlink.framework ~/Library/Frameworks/


In my appended version, the main modifications were to the file Makefile.osx.  For everything to compile properly the new makefile changes the CADDSDIR to point to ${MLINKDIR}/CompilerAdditions, deletes the SYS path, specifies CC=g++, and adds -lstdc++ before -framework CoreFoundation.  Simple examples on how to use pythonkia can be found in the Pythonika.nb file on the google codes site.

Web Search Queries Predict Stock Market Trading Volumes, really?

After reading "Web search queries can predict stock market volumes" I decided to replicate the study using Google Insights for Search to look for more meaningful trends.  A more in-depth post will be done later, here I am just presenting some cautious considerations for the readers of the study.

Part of the curious methodology of the paper was its filtering of non-working days.  Using "AAPL" as an example, we can see why.  How would the inclusion of the increased weekend queries influence the tests for granger causality?


Normalized data of daily trading and query volumes for AAPL excluding weekends for last 90 days

Normalized data of daily trading and query volumes for AAPL with weekends for last 90 days

Wednesday, October 19, 2011

American Psycho Business Cards in Latex

I recently tried to find a latex business card template that was similar in design to the cards seen in American Psycho.  I thought Patrick Bateman was the easiest non-Gordon Gekko face saving costume for those Halloween parties, where you are not sure if a costume is required.  Because I can explain to my boss why I am carrying a chain saw in my Valentino suit, but not why I am dressed as Frankenstein's monster.  I was disappointed that no one had posted a template, but extremely happy for a chance to be the first.  I started by borrowing a simple latex business card template from Mike Elery's website.  After playing with the alignment and fonts I was able to create a decent Patrick Bateman card.



Image from vaultofthebankrobber.blogspot.com


It was disappointing to discover that there was no Silian Rail font and no accepted RGB or CMYK of bone color.  The latex font called Palatino, in my opinion, is the closest matching font to Silian Rail.  Since ivory is a bone, I used a ivory background.  

The only deviation from the movie prop is my correct spelling of 'Acquisition.'  A misspelling I did not notice before my attempt to replicate the card.  I think this misspelling was necessary to create the perfect alignment with the company name, which cannot be done simply by shrinking the font or adjusting the letter spacing.  It does add an extra symbolic metaphor that gives me a greater appreciation for the movie.

The PDF output was designed for the business card paper I bought on sale.  If anyone needs to change the output to Avery's brand paper or any other sizing just leave a comment for help.

For fun here is Bateman's Mr. Hyde version of his business card.




Here is the tex sourcefile.