Excel and The London Whale

The problems of using Excel within financial institutions are well-known – the control risks are huge because it’s so easy for a rogue trader to manually edit trade data/market data and re-save the sheet. This article describes the role Excel played in under-estimating the risks involved in financing The London Whale’s trading strategies:

JPMor­gan’s Chief Invest­ment Office need­ed a new value-at-risk (VaR) model for the syn­thet­ic cred­it port­fo­lio (the one that blew up) and assigned a quan­ti­ta­tive whiz (“a London-based quan­ti­ta­tive expert, math­e­mati­cian and model devel­op­er” who pre­vi­ous­ly worked at a com­pa­ny that built ana­lyt­i­cal mod­els) to cre­ate it. The new model “oper­at­ed through a series of Excel spread­sheets, which had to be com­plet­ed man­u­al­ly, by a process of copy­ing and past­ing data from one spread­sheet to another.”

Another question is, how do you test a spreadsheet? And how do you re-use fragments of a sheet?

the spread­sheets that peo­ple cre­ate with Excel are incred­i­bly frag­ile. There is no way to trace where your data come from, there’s no audit trail (so you can over­type num­bers and not know it), and there’s no easy way to test spread­sheets

Leave a comment

Filed under Finance

Qualities of Uber-Productive people

Great article on how to achieve high productivity.

Productive people aren’t braver than others; they just find the strength to keep moving forward. They realize fear is paralyzing while action creates confidence and self-assurance.

I subscribe to the school of thought that, in order to finish a project, you have to keep starting – to get over the fear of imperfection, you don’t focus on completion, but focus on beginning again and again.

Think about a time you put off a task, finally got started, and then, once into it, thought, “I don’t know why I kept putting this off–it’s going really well. And it didn’t turn out to be nearly as hard as I imagined.”

Read more: http://www.inc.com/jeff-haden/7-qualities-of-uber-productive-people.html#ixzz2KoR5fDv8

Leave a comment

Filed under Soft skills

Introduction to C++11 Concurrency

Marius Bancila wrote a neat introduction to C++11 concurrency.

Leave a comment

Filed under C++

Apple SmartWatch – yes please!

When I awoke this morning, I didn’t know that I wanted a smart watch. Having read this article, though, I’ve realised my set of gadgetry won’t be complete until I get one. The reviews of the currently available smart watches weren’t very complimentary, so I’ll wait to see what Apple come up with.

Leave a comment

Filed under Technology

How to write managed C++ using templates

Occasionally, I write some managed C++ code as a glue-layer between C++ and F#. Today was such an occasion, and I found myself writing the same piece of code in several places with different types. Obviously, my reaction was to refactor to share the common code – given that the behaviour was common and independent of the underlying type, a template class seemed appropriate – but can you use templates with managed C++?

It turns out that you can – here’s the code, the aim of which was to take some COM object from native code and wrap it as an option of some expected strong type. If you haven’t seen managed C++ before, the syntax looks pretty ghastly – it may help to mentally substitute & for ^. If you aren’t familiar with F# option, it’s like boost::optional;.

template<typename T>
FSharpOption<T^>^ getOptional( IUnknown* raw )
{
  FSharpOption<T^>^ optionalValue = 
    optionalValue = FSharpOption<T^>::None

  if ( raw != nullptr )
  {
    T^ cooked = (T^)Marshal::GetObjectForIUnknown(IntPtr( raw ));
    if (cooked != nullptr)
      optionalValue = FSharpOption<T^>::Some(cooked);
  }
  return optionalValue;
}

Here’s how you would call the template function to get back the managed C++ equivalent of the F# type MyType option:

FSharpOption<MyType^>^ myValue = getOptional<MyType>( _rawValue );

Leave a comment

Filed under C++

Software code should read like well-written prose

I’ve long felt that well written software should not only be human-readable, it should be a good read. It’s a view held by Robert Martin who describes clean code as elegant, efficient, readable like well-written prose.

This came to mind when I finished reading a thriller, “The Lion” by Nelson DeMille. I’ve read several of his books, not least “The Charm School” which was brilliant. Now, The Lion didn’t have a great plot – in fact, having read a couple of his John Corey books already, I could pretty much predict the finale after the first couple of chapters. But it didn’t matter, because the story was so well told I enjoyed the journey. The next book I picked up is a science fiction tale set around the time of World War II but with a time-travelling twist – it has an exciting plot and I haven’t a clue what will happen. Yet it’s less enjoyable, the prose is stodgy and I’m struggling to get to know the characters.

Now, to me, the plot in a novel is analogous to software design, whereas the story telling is analogous to the implementation code. Whilst I’d prefer good story telling with a weak plot to a great plot with poor prose, the opposite is true of software – good design trumps good implementation code every time. That’s where software and fiction are so different – software is alive and will be maintained and extended throughout its life, whereas a novel is frozen in time the moment the author deems it finished. You can always re-implement badly implemented pieces of code – but it’s a much bigger task to re-work an entire design.

1 Comment

Filed under Programming

Lessons on hiring

Good article about an unexpected problem from hiring too many B-players in your firm. Here are the author’s definitions:

A player: Fully self-sufficient and takes initiative that positively impacts the company.
B player: Does some things well, but not fully self-sufficient, and not consistently strong.
C player: Just average, and does not excel in any area.
D player: Poor performer, and shouldn’t last long if you are a half-capable manager.
F player: Should be out…like yesterday.

Here’s the problem with B-players, the inconsistency catches you by surprise the first time, so then they need careful monitoring – something you don’t have time to do.

When you have someone on your team that you think is doing well enough, you will likely trust them with mission-critical tasks like hiring or pushing code. This will impact the entire evolution of your company. If you entrust important decisions to someone who is just “good enough,” you will watch the opportunities pass.

The author claims that a star engineer isn’t just worth 10x the average, s/he is irreplaceable by any number of lower quality people.

Leave a comment

Filed under Soft skills

Thesis Whisperer's avatarThe Thesis Whisperer

This post is by Julio Peironcely, founder and editor of the Next Scientist blog. Julio is a PhD student in Metabolomics and Metabolite Identification at Leiden University, The Netherlands and has been blogging and using social media for several years, both for fun and for professional purposes.

This post developed out of a conversation on Twitter about the difficulties of socialising at academic conferences, particularly at the dinner.  I was thrilled when Julio sent me this post which is a comprehensive set of advice which anyone, scientist or not, can benefit from. Take it away Julio!

conference dinnerYou didn’t meet anybody new at the last scientific conference.

You paid high registration fees, travelled to the other side of the world, listened to boring talks, nobody came to your poster.

At least you met interesting people at the conference dinner, didn’t you?

Well, it’s kind of hard when you are…

View original post 1,533 more words

Leave a comment

Filed under Uncategorized

Concurrency with C++11

Having watched Herb Sutter’s C++ Concurrency video, I wanted to try out a few of the techniques for myself. The first step was to write a simple synchronised queue, which he left as an exercise for the reader.  The key feature is that pop() blocks until an element is pushed into the queue – then it returns the element.  This turns out to be pretty succinct using C++11 features like std::mutex and std::condition_variable:

namespace musingstudio
{
  template<typename T>
  class SynchronizedQueue
  {
    std::deque<T> m_queue;
    std::mutex m_mutex;
    std::condition_variable m_wait_for_non_empty;

  public:
    // When an element of T is pushed onto the queue,
    // one caller waiting in a pop() call will be notified
    void push( const T& t )
    {
      std::unique_lock<std::mutex> lock(m_mutex);
      m_queue.push_back(t);
      m_wait_for_non_empty.notify_one();
    }

    // Calls to pop() will block until an element of T is 
    // pushed onto the queue
    T pop()
    {
      std::unique_lock<std::mutex> lock(m_mutex);
      while(m_queue.empty())
      {
        m_wait_for_non_empty.wait(lock);
      }
      T tmp(m_queue.front());
      m_queue.pop_front();
      return tmp;
    }
  };
}

and here’s some code to exercise it:

void testConcurrentQueue()
{
  musingstudio::SynchronizedQueue<int> elements;

  std::thread pusher([&]()
  {
    for (int i = 0; i < 5; ++i)
    {
      wait();
      std::cout << "Pushing " << i << '\n';
      elements.push(i);
    }
  });

  std::thread popper([&]()
  {
    for (int j = 0; j < 5; ++j )
    {
      int popped = elements.pop();
      std::cout << "Popped " << popped << "\n";
    }
  });

  pusher.join();
  popper.join();
}

Output:

SynchronizedQueueOutput

The next item that caught my eye was a template class that wraps an instance of T so that access to it becomes transactional across threads. No need to explicitly take a lock for each group of calls to the object – instead, you express each transaction on on the instance of T as a lambda. A mutex blocks and the command (expressed as a lambda) is executed in the calling thread.  Herb called his example Monitor<T>, but I preferred Sequential<T> as a partner to Concurrent<T> (see below).  Also, I replaced operator() with excute() (in my opinion it’s easier to read).  Typical use looks like this:

Sequential<T> t( ... ); 
t.execute([&](T& u)
{  
  /* perform multiple operations in this lambda as one synchronised transaction*/  
});

So much for the context – here’s the implementation:

namespace musingstudio
{
  template<typename T>
  class Sequential
  {
    mutable T m_t;
    mutable std::mutex m_mutex;
  public:
    Sequential( T t ) : m_t( t )
    {
    }
    template<typename F>
    auto execute( F f ) const -> decltype(f(m_t))
    {
      std::unique_lock<std::mutex> lock(m_mutex);
      return f(m_t);
    }
  };
}

And here’s the code in action, using Sequential<ostream&> to synchronise calls to std::cout:

void testSequential()
{
  musingstudio::Sequential<std::ostream&> sync_cout( std::cout );
  auto doPush = [&]() 
  {
    for ( int i = 0; i < 10; ++i )
    {
      sync_cout.execute([&](std::ostream& os)
      {
        os << i << i << i << i << i << "\n";
      });
    }
  };
  std::thread thread1(doPush);
  std::thread thread2(doPush);
  thread1.join();
  thread2.join();
}

Output:

SequentialOutput

Now that we’ve got SynchronizedQueue<T> and Sequential<T>, here’s Concurrent<T> which provides a way to perform a series of synchronised operations on some object in parallel with the activity on the main thread.  For example, if you need to keep a GUI thread responsive.  I love the idea of pushing a “Done” event onto the message queue in the destructor so that queued work is concluded and then Concurrent<T> returns.  This is also a very nice use for std::future and std::promise – allow the caller to keep the return value as a future, but don’t block until it’s needed.

template<typename T>
class Concurrent
{
  mutable T m_t;
  mutable SynchronizedQueue<std::function<void()>> m_queue;
  bool m_done;
  std::thread m_worker;
  // Assign value to the promise where there's a 
  // non-trivial return type
  template<typename Ret, typename Ftn, typename T>
  void setValue( std::promise<Ret>& promise, Ftn& f, T& t ) const
  {
    promise.set_value( f(t) );
  }
  // Assign void to the promise - trivial void return type
  template<typename Ftn, typename T>
  void setValue( std::promise<void>& promise, Ftn& f, T& t ) const
  {
    f(t);
    promise.set_value();
  }
public:
  Concurrent( T t ) : m_t(t), m_done(false), 
    m_worker( [=](){ while(!this->m_done){ m_queue.pop()(); }} )
  {}
  ~Concurrent()
  {
    m_queue.push( [=]{ this->m_done = true; } );
    m_worker.join();
  }
  // In order to return a value from the operation that we 
  // process on another thread, use async, promises and futures 
  // - we can't just return the calculated value,
  // because then the caller would have to block.
  template<typename F>
  auto execute( F f ) const -> std::future<decltype(f(m_t))>
  {
    auto promise = 
      std::make_shared<std::promise<decltype(f(m_t))>>();
    auto return_value = promise->get_future();
    m_queue.push( [=]()
    { 
      try
      {
        setValue( *promise, f, m_t );
      }
      catch(...)
      { promise->set_exception( std::current_exception() ); }
    });
    return return_value;
 }
};

Here’s some code to exercise Concurrent<T>:

void testConcurrentReturningFunction()
{
  musingstudio::Concurrent<std::string> words("Concurrent<T> - ");
  std::vector<std::future<std::string>> values;
  // Set off the calculations in a worker thread, storing future return values
  for ( size_t i = 0; i < 10; ++i )
  {
    values.push_back( 
      words.execute( [=]( std::string& in )
      {
        in += std::to_string(i);
        return in;
      }) );
  }
  // Now collection the return values and display them
  std::for_each( values.begin(), values.end(), [](std::future<std::string>& f)
  {
    std::cout << f.get() << "\n";
  });
}

Output:

ConcurrentOutput

7 Comments

Filed under C++ Code

Silent Circle launches new encryption app

Silent Circle have announced a new encryption app:

The technology uses a sophisticated peer-to-peer encryption technique that allows users to send encrypted files of up to 60 megabytes through a “Silent Text” app.

“We feel that every citizen has a right to communicate,” Janke says, “the right to send data without the fear of it being grabbed out of the air and used by criminals, stored by governments, and aggregated by companies that sell it.”

I can see the practical value in this (for example, if you need to send sensitive documents from work to home), as well as the human rights slant that the article explores.

Leave a comment

Filed under Technology