Book Image

NumPy Cookbook

Book Image

NumPy Cookbook

Overview of this book

Today's world of science and technology is all about speed and flexibility. When it comes to scientific computing, NumPy is on the top of the list. NumPy will give you both speed and high productivity. "NumPy Cookbook" will teach you all about NumPy, a leading scientific computing library. NumPy replaces a lot of the functionality of Matlab and Mathematica, but in contrast to those products, it is free and open source. "Numpy Cookbook" will teach you to write readable, efficient, and fast code that is as close to the language of Mathematics as much as possible with the cutting edge open source NumPy software library. You will learn about installing and using NumPy and related concepts. At the end of the book, we will explore related scientific computing projects. This book will give you a solid foundation in NumPy arrays and universal functions. You will also learn about plotting with Matplotlib and the related SciPy project through examples. "NumPy Cookbook" will help you to be productive with NumPy and write clean and fast code.
Table of Contents (17 chapters)
NumPy Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Simulating trading at random


In the previous recipe, we tried out a trading idea. However, we have no benchmark that can tell us if the result we got was any good. It is common in such cases to trade at random, under the assumption that we should be able to beat a random process. We will simulate trading by taking some random days from a trading year. This should illustrate working with random numbers using NumPy.

Getting ready

If necessary, install Matplotlib. Refer to the See Also section for the corresponding recipe.

How to do it...

First, we need an array filled with random integers.

  1. Generate random indices.

    Generate random integers with the NumPy randint function. This will be linked to random days of a trading year:

    return numpy.random.randint(0, high, size)
  2. Simulate trades.

    Simulate trades with the random indices from the previous step. Use the NumPy take function to extract random close prices from the array of step 1:

    buys = numpy.take(close, get_indices(len(close), nbuys))
    sells = numpy...