Wednesday, August 6, 2014

Predicting Monthly Car Sales for Brands in US: First Step

I've set out to produce monthly forecasts of monthly car sales by brand in the US. So far I've made a SUTSE dynamic linear model (code on Github) and created a Shiny app (http://sweiss.shinyapps.io/carvis/) as a prototype (no predictions yet).

Basically, I want to combine my interest in cars with my interest in stats.

My current roadblock is the how slow the code runs, but I intend to have a speedy implementation using RStan by next month.

If anyone has tips or suggestions, please comment!






Predictions for September:
Acura & 13764.75 \\
  Audi & 15929.24 \\
  BMW & 26445.80 \\
  Buick & 23725.69 \\
  Cadillac & 16722.01 \\
  Chevrolet & 204636.69 \\
  Chrysler & 26336.27 \\
  Dodge & 51082.20 \\
  Fiat & 4408.64 \\
  Ford & 228880.56 \\
  GMC & 50361.17 \\
  Honda & 143487.90 \\
  Hyundai & 67112.10 \\
  Infiniti & 10366.93 \\
  Jaguar & 1162.72 \\
  Jeep & 60577.05 \\
  Kia & 53863.38 \\
  Land.Rover & 4736.08 \\
  Lexus & 30614.06 \\
  Lincoln & 7766.23 \\
  Mazda & 29544.19 \\
  Mercedes.Benz & 28693.43 \\
  Mini & 5455.48 \\
  Mitsubishi & 6706.69 \\
  Nissan & 125118.79 \\
  Porsche & 3914.65 \\
  Ram & 39194.54 \\
  Smart & 1258.65 \\
  Subaru & 46186.21 \\
  Toyota & 213761.40 \\
  Volkswagen & 31581.44 \\
  Volvo & 4809.14 \\






Wednesday, July 23, 2014

Mideast Graph 3: Slate Middle East Friendship

Slate recently published a great info-graphic about Middle-East Relationships. It shows the relationships (Friend, Enemy, or Complicated) of 13 countries / organizations and the relationships between each pair. One draw back of the chart is that it doesn't show if countries / organizations cluster among each other. This post will attempt to rectify that drawback. 

From a previous post, I used an matrix decomposition of the laplacian matrix and plotted the smallest two eigenvectors against each other. The graphs below follow the same methodology and you can find code here. To give weights to the network matrix, I assigned values of 1, -1, and 0 for Friend, Enemy, and Complicated. 

Below is the resulting graph with red lines indicating Enemy and blue lines indicated Friends.  




The above graph shows 3 possible clusters. Turkey, Palestinian Authority, and Hamas are close to each other in lower left corner. In top right there is United States, Egypt, and Israel. Lower Left shows Iraq, Syria, Hezbollah and Iran.  

Since both ISIS and Al-Qaida have no Friend relationships and the goal of this was to see if there were clusters of friends / enemies I removed these organizations and redid analysis. Below is the result.


Here we can see much clearer distinction of relationship clusters. United States, Israel, and Egypt form one with Saudi Arabia as possibly a 'member' of that group. Iraq, Syria, Hezbollah and Iran have a defined cluster, which makes sense as they are all dominated by Shias. Finally, there is Turkey, Palestinian Authority and Hamas. I was surprised to see Turkey so close with Palestinian Authority and Hamas. But seeing as Turkey has been a supporter of Palestinians now and in past, maybe I shouldn't be. Also, surprising that there are no Arab countries close with Palestinians now.

The Mideast Conflict is sort of a 3 way standoff with Shias in one corner, Sunnis friendly to US / Israel in another, and Turkey trying to gain influence in a region it once controlled in the final corner.


Github

Thursday, May 22, 2014

didYouMean() Function: Using Google to correct errors in Strings

A function that will take a String as an input and return the "Did you mean.." or "Showing Results for.." from google.com. Good for misspelled names or locations.


library(RCurl)
##if on windows might need: options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
didYouMean=function(input){
  input=gsub(" ", "+", input)
  doc=getURL(paste("https://www.google.com/search?q=",input,"/", sep=""))
  
  
  dym=gregexpr(pattern ='Did you mean',doc)
  srf=gregexpr(pattern ='Showing results for',doc)
  
  
  if(length(dym[[1]])>1){
    doc2=substring(doc,dym[[1]][1],dym[[1]][1]+1000)
    s1=gregexpr("?q=",doc2)
    s2=gregexpr("/&",doc2)
    new.text=substring(doc2,s1[[1]][1]+2,s2[[1]][1]-1)
    return(gsub("[+]"," ",new.text))
    break
  }
  
  else if(srf[[1]][1]!=-1){
    doc2=substring(doc,srf[[1]][1],srf[[1]][1]+1000)
    s1=gregexpr("?q=",doc2)
    s2=gregexpr("/&",doc2)
    new.text=substring(doc2,s1[[1]][1]+2,s2[[1]][1]-1)
    return(gsub("[+]"," ",new.text))
    break
  }
  else(return(gsub("[+]"," ",input)))
}  

So didYouMean("gorecge washington") returns "george washington"


Works well with misspelled companies or nouns or phrases. For example; you're doing text analysis on twitter and a customer raves about Carlsburg beer. Only problem is he's enjoying their product while tweeting (something that happens only rarely, I'm sure) and wrote "clarsburg gprou". Not to worry!

> didYouMean("clarsburg gprou")
[1] "carlsberg group"

Or suppose you have a 3 phase plan for profits. This can help you get there!

didYouMean("clletc nuderpants")
[1] "collect underpants"

Saturday, May 17, 2014

Modelling This Time is Different: Corrected

New PDF
New Code


I made two errors in my previous post.

The first is that I put Probability in the utility function. Generally, this is a no no where the E[utility]=sum over i: P(outcome i)*U(outcome i). I therefore changed it to a more simple maximization problem (no Lagrangian multipliers necessary) where the individual maximizes E[Profits].

 The second problem has to deal with maximizing subject to probabilities. Since I sampled from the joint posterior distribution of unknown parameters, I had a number of draws from the distribution. What I did in the previous analysis was maximize each pair of simulated draws individually, and then averaged over these maximized results to get what I thought was the optimal result. In general, this method does not result in the optimal value. I should have maximized all pairs simultaneously. Basically I did E[max s of f(s,p)] instead of max s of E[f(s,a)].

In general, the results are superficially similar to my original analysis. Even if the results are largely the same, its best to describe my mistakes upfront, and avoid awkward questions later. 

Monday, April 14, 2014

Modeling "This Time is Different" in R

***WHOOPS Made some mistakes in analysis. Update HERE***


Check out PDF for Equations
And Code to run yourself

Introduction:
“This Time is different” by Reinhart and Rogoff is an empirical history of financial crises and panics.  It describes many economic events such as; inflation, bubbles, and defaults.

The theme that ties these events together is the idea that people have an unrealistic expectation of the future because they believe “This time is different”. With this new belief, they act in a way as to cause the next crisis.

While the book dealt with the empirical investigation of the matter, it didn’t describe the theme itself in intricate detail. This post will attempt to fill that void by giving a mathematical interpretation of the theme.

There are 3 aspects of the model I’d like to capture,
1.     prior beliefs act guide and tell us how to make decisions
2.     decisions have an effect on the future
3.     people update our beliefs when new information becomes available

Economic Maximization Problem:
I came up with a simple driving example that describes these properties.  Suppose we’d like to maximize the speed of a car and minimize the probability of a crash (or maximize probability of not crashing). However, the probability of a car crashing is dependent on the speed. This can be described as a utility maximization problem described below, where we maximize subject to a constraint.

Maximize:

Utility(Speed,Probability of Not Crashing) = (Speed^a)*(Probability of not crashing ^(1-a))

Subject to:

Probability of Not Crashing = B*log(1/speed-1) + C

Where B and  C  are the constant and slope parameters of an inverse logistic function and a is tradeoff for utility function between the two goods (Probability of not crashing and Speed).
(Look in PDF for optimal solution)

Bayesian Updating Problem:

Described so far the problem is a fairly straightforward maximization problem. However, in this model, the parameters B and C are unknown to the individual. While there is a true function for the relationship between Speed and probability of not crashing  (that is a true B and C) the individual doesn’t know it.

Bayesian statistics seems like a natural to model the individual’s beliefs over these parameters. With this prior belief over parameters, he maximizes his utility subject to it and makes a decision in each time period. When new information becomes he updates his prior information and uses this to make a new decision. In this sense, the system is dynamic and a time series can be produced.

Unfortunately, I don’t believe there is a closed form solution to updating Bayesian logistic regression. Therefore, I used RSTAN to simulate from the posterior distributions (Code shown at end).

I set the model with parameters of with, a=.05, B=1, and C=100. The initial prior probabilities are parameters C~N(100,5) and B~N(1,.05) ,  where N(x,y) is a normal distribution with mean x and stdev y.  Below is one example of a simulated time series.

 



As you can see, the individual is learning the true parameters as he goes through time. When a crash occurs, he dramatically reduces his decision and if a crash doesn’t occur, he slightly increased his decision. This can be seen as a smoothed over “this time is different” where the actor adjusts his decision more optimistically until a negative event happen, in which case, he changes his decision more abruptly.

The optimum decision is shown in the blue horizontal line, and while the actor doesn’t achieve it in this example, he will eventually (… I think) as this is the equilibrium.

Conclusion:
The purpose of this post was to describe a mathematical interpretation of “This Time is Different”. I did this by solving a maximization problem, with unknown parameters, and then updating those parameters using the Bayesian Framework.

While the example I used was only relation to speed and car crashes, I don’t think its much of a stretch to use this model to describe economic events. An example of might be that a bank wants to have an optimal amount of amount of capital requirements vs event of bankruptcy for a bank. (The smaller capital requirements, the higher the expected profits, and higher probability of bankruptcy.)



Modeling "This Time is Different"

***WHOOPS Made some mistakes in analysis. Update HERE***
Check out PDF for Equations
And Code to run yourself

Introduction:
“This Time is different” by Reinhart and Rogoff is an empirical history of financial crises and panics.  It describes many economic events such as; inflation, bubbles, and defaults.

The theme that ties these events together is the idea that people have an unrealistic expectation of the future because they believe “This time is different”. With this new belief, they act in a way as to cause the next crisis.

While the book dealt with the empirical investigation of the matter, it didn’t describe the theme itself in intricate detail. This post will attempt to fill that void by giving a mathematical interpretation of the theme.

There are 3 aspects of the model I’d like to capture,
1.     prior beliefs act guide and tell us how to make decisions
2.     decisions have an effect on the future
3.     people update our beliefs when new information becomes available

Economic Maximization Problem:
I came up with a simple driving example that describes these properties.  Suppose we’d like to maximize the speed of a car and minimize the probability of a crash (or maximize probability of not crashing). However, the probability of a car crashing is dependent on the speed. This can be described as a utility maximization problem described below, where we maximize subject to a constraint.

Maximize:

Utility(Speed,Probability of Not Crashing) = (Speed^a)*(Probability of not crashing ^(1-a))

Subject to:

Probability of Not Crashing = B*log(1/speed-1) + C

Where B and  C  are the constant and slope parameters of an inverse logistic function and a is tradeoff for utility function between the two goods (Probability of not crashing and Speed).
(Look in PDF for optimal solution)

Bayesian Updating Problem:

Described so far the problem is a fairly straightforward maximization problem. However, in this model, the parameters B and C are unknown to the individual. While there is a true function for the relationship between Speed and probability of not crashing  (that is a true B and C) the individual doesn’t know it.

Bayesian statistics seems like a natural to model the individual’s beliefs over these parameters. With this prior belief over parameters, he maximizes his utility subject to it and makes a decision in each time period. When new information becomes he updates his prior information and uses this to make a new decision. In this sense, the system is dynamic and a time series can be produced.

Unfortunately, I don’t believe there is a closed form solution to updating Bayesian logistic regression. Therefore, I used RSTAN to simulate from the posterior distributions (Code shown at end).

I set the model with parameters of with, a=.05, B=1, and C=100. The initial prior probabilities are parameters C~N(100,5) and B~N(1,.05) ,  where N(x,y) is a normal distribution with mean x and stdev y.  Below is one example of a simulated time series.

 



As you can see, the individual is learning the true parameters as he goes through time. When a crash occurs, he dramatically reduces his decision and if a crash doesn’t occur, he slightly increased his decision. This can be seen as a smoothed over “this time is different” where the actor adjusts his decision more optimistically until a negative event happen, in which case, he changes his decision more abruptly.

The optimum decision is shown in the blue horizontal line, and while the actor doesn’t achieve it in this example, he will eventually (… I think) as this is the equilibrium.

Conclusion:
The purpose of this post was to describe a mathematical interpretation of “This Time is Different”. I did this by solving a maximization problem, with unknown parameters, and then updating those parameters using the Bayesian Framework.

While the example I used was only relation to speed and car crashes, I don’t think its much of a stretch to use this model to describe economic events. An example of might be that a bank wants to have an optimal amount of amount of capital requirements vs event of bankruptcy for a bank. (The smaller capital requirements, the higher the expected profits, and higher probability of bankruptcy.)



Saturday, January 25, 2014

Economist Year in Review: Part 3

Finally, I want to show a network graph of countries based on the correlations using LDA. I used qgraph() in R. Kind of interesting how Switzerland and Norway are outside the main European Cluster.