Twitter: raymondcamden


Address: Lafayette, LA, USA

Experiment - Build your own stock market AI

10-15-2012 3,849 views JavaScript 4 Comments

I had an interesting idea last night. I'm not saying it is a good idea - my brain is having some serious weirdness going on with the seven hour time change. But good idea or not I built it and figured I'd share it.

Did you know that you could create functions in JavaScript by passing in a string? I don't see many people using this technique (ok, I've never seen anyone use this) but the gist is that you can create a new Function object by listing any number of arguments followed by a string of code. Here is an example:

This got me thinking about what kind of code would make use of this form of defining functions. About four years ago I asked my readers to participate in a coding contest that required you to write the logic to handle a lemonade stand. The contest had you writing a UDF that responded to daily weather reports. It passed you information about your assets and you simply responded with an action. The idea was that you were building an "intelligent agent" to handle the business.

With this in mind, I decided to build something similar in JavaScript. In my simulation, you are writing an agent that monitors a stock and decides when to buy or sell stock. Your code will be a function that is passed basic data like the stock price, the change, etc. You then handle returning an action: Buy stock, Sell stock, do nothing.

You are given a simple function to start off with:

When you click the Start Simulation button, I take that code and generate a function from it:

The try/catch there handles some errors, but not all. As the code runs the simulation, I've got to do more error handling on the processing side. Here is that logic:

It could use a bit more hardening, but you can see the basics of what I'm doing here. As the simulation runs you see a running report of your stats.

So - want to give it a shot? Stock Market AI Simulator

In case you are curious - you can absolutely cheat with this. I don't look for sneaky things like selling negative amounts of stock. Nor do I block you from reaching out into the global scope and manipulating your values. I'd love to see what people try in the demo. Post your examples as comments below.

4 Comments

  • Commented on 10-15-2012 at 12:59 PM
    I'll definitely be playing with this more later since it's fun! I just did simple stuff, didn't really go to deep with it. If I think about it I'd probably due detailed value tracking to make better decisions on what action to take but for keeping it simple this did a decent job of not staying right around our starting value.

    var result = {};
    / keep track of what turn we are on /
    if ( storage.count == undefined ) {
    storage.count = 1
    }
    / increment turn /
    storage = {
    count: count++
    }
    / if we have cash and the stock is considerably down, buy max /
    if( cash > 500 && change < -5 ) {
    result.action="buy";
    result.quantity= Math.floor( cash / value ) ;
    / only a small gain, hold /
    } else if ( change > 0 && change < 3 ) {
    result.action="hold";
    / Stock is on a fairly large gain, dump it all /
    } else if ( change > 3 ) {
    result.action="sell";
    result.quantity = shares;
    } else {
    result.action="hold";
    }
    / if at end of game sell everything! /
    if ( storage.count == 99 ) {
    result = {
    action:"sell",
    quantity:shares
    }
    }
    return result;
  • Commented on 10-15-2012 at 1:01 PM
    I forgot to mention the only thing probably worth taking out of my code is the turn track with the final stock dump at the very end!
  • Commented on 10-15-2012 at 5:15 PM
    Can't believe no on else at least posted playing with this thing. I finally got a chance to play a little more.

    Purchasing is just based off cumulative averages. Nothing special, just thought it was fun to play with!

    / initialize our base storage values /
    initValues( value );
    var result = {};

    / BUY RULE /
    if( cash > 500 && ( getCumulativeAverage() - value ) > 20 ) {
       result.action = "buy";
       result.quantity= Math.floor( cash / value );
       storage.lastBuyValue = value;
    / SELL RULE /
    } else if ( ( value - getCumulativeAverage() ) > 15 ) {
       result.action="sell";
       result.quantity = shares;
    / DEFAULT ACTION /
    } else {
       result.action="hold";
    }


    / first turn, buy max because minValue of stock is always decent /
    if ( count == 1 ) {
       result.action="buy";
       result.quantity= Math.floor( cash / value );
       storage.lastBuyValue = value;
    }
    / if at end of game sell everything! /
    if ( count == 99 ) {
       result = {
       action:"sell",
       quantity:shares
       };
    }
    / track this transaction /
    trackTransaction( value, shares, cash, result, storage );
    / update cumulative average /
    calcCumulativeAverage( value, count );

    return result;

    function getCumulativeAverage() { return storage.cumuluativeAverage; }

    function
    initValues( value ) {
       / Init tracking variables /
       if ( storage.arrTransactions === undefined ) {
          storage.arrTransactions = []
       }
       if ( storage.initialValue === undefined ) {
          storage.initialValue = value;
       }
       if ( storage.cumuluativeAverage === undefined ) {
          storage.cumuluativeAverage = value;
       }
       if ( storage.arrHistory === undefined ) {
          storage.arrHistory = [];
       }
    }

    function calcCumulativeAverage( value, count) {
       var i = 0;
       var sum = 0;
       for ( i = 0; i < storage.arrHistory.length; i++ ) {
          sum+= storage.arrHistory[i];
       }
       storage.cumuluativeAverage = sum / count;
    }

    function
    trackTransaction( value, shares, cash, result ) {
       / Transaction tracking /
       if ( ( result.action == "buy" || result.action == "sell" ) && result.quantity > 0 ) {
          transaction = {
             value: value,
             shares: shares,
             cash: cash,
             action: result.action,
             quantity: result.quantity,
             cumuluativeAverage: storage.cumuluativeAverage,
             lastBuyValue: storage.lastBuyValue
          }
          storage.arrTransactions.push( transaction );
       }
       / Track Value History /
       storage.arrHistory.push( value );
    }
  • Commented on 10-16-2012 at 12:34 AM
    CJM: It has been my experience that the blog posts I think people will comment heavily on... are not. ;) I'm glad your enjoying it, and thank you for posting your code!

Post Reply

Please refrain from posting large blocks of code as a comment. Use Pastebin or Gists instead. Text wrapped in asterisks (*) will be bold and text wrapped in underscores (_) will be italicized.

Leave this field empty