2012 Python Meme

My “Python meme” replies.

What’s the coolest Python application, framework or library you have discovered in 2011?

NumPy, because of my book Numpy 1.5 Beginner’s Guide published in November this year. Although I did not discover it in 2011. Still I learned a lot of things about NumPy in the process, so it was a rediscovery, if you will. Yes, NumPy is supercool. Trust me, I am an expert on cool.

What new programming technique did you learn in 2011?

I can’t tell you that, it’s all strictly confidential, top secret stuff. I think I said too much already. OK, I learned some basic AI techniques. Nothing special. I did some spikes with SQLAlchemy too.

What’s the name of the open source project you contributed the most in 2011? What did you do?

NumPy. I hope that I contributed to NumPy through my blog and book. Evangelist is a Big Word, so I would not use that one to describe my contribution. Let’s say, I am an Apprentice Evangelist. In training.

What was the Python blog or website you read the most in 2011?

I have been reading the NumPy, SciPy and Matplotlib online documentation a lot.

What are the three top things you want to learn in 2012?

That’s easy.

  1. (Internet) marketing.

  2. Social media.

  3. Artificial intelligence, machine learning and natural language processing.

The first two items I want to learn mostly because of my book. I am exploring social media, which means in practice that I joined a lot of websites and created profiles. The list is on the social section of the unofficial book website. If you Like me, I will Like you back. If you Follow me, I will Follow you back, I promise. Let’s be friends! The last item is something I always wanted to do. I always dreamed of having a robot or computer do all my hard work.

What are the top software, app or lib you wish someone would write in 2012?

I really like VisualVM, which is a Java profiling tool. I haven’t found a Python equivalent yet, so please write one. Also I want it to be easy to use and install.

Want to do your own list? here’s how:

copy-paste the questions and answer to them in your blog tweet it with the #2012pythonmeme hashtag


I would like to thank Gokhan Sever for his recent review of NumPy Beginner’s Guide on the Pycloud blog. Happy New Year, readers! I wish you all the best for 2012!

Share
Posted in programming | Tagged | Leave a comment

Christmas NumPy Book Giveaway

Merry Christmas, dear readers!

Since it’s the season of giving, Packt Publishing offered to organize a contest with prize – 2 print copies and 2 ebooks of my book NumPy Beginner’s Guide.

The Prize

NumPy Beginner's Guide Front Cover

What you will learn from NumPy 1.5 Beginner’s Guide

  • Installing NumPy
  • Learn to load arrays from files and write arrays to files
  • Work with universal functions
  • Create NumPy matrices
  • Use basic modules that NumPy offers
  • Write unit tests for NumPy code
  • Plot mathematical NumPy results with Matplotlib
  • Integrate with Scipy, a high level Python scientific computing framework built on top of NumPy

The book is written in beginner’s guide style with each aspect of NumPy demonstrated by real world examples. You can also download a sample chapter.

How to Win NumPy Beginner’s Guide

You can enter by writing a comment to this post explaining why you would like to have the book. The contest has already started and will end on January 31st 2012 at 11:59 PM GMT. Winners will be randomly chosen and notified by email, after termination of the contest.

The contest is open to everybody in the world, however print copies are only available to residents of the US and Europe.

Comments are moderated by me, so your comment will not appear immediately.

Good luck, readers!

Share
Posted in books, programming | Tagged , , | 46 Comments

Steady State Vector of Markov Chains

This entry is part 9 of 17 in the series Numpy Strategies

Numpy Strategies 0.1.3

Unlucky Sprint 13. Scary, especially if you suffer from Triskaidekaphobia. The task for this sprint:

  • Determine the steady state vector of our Markov chain model.

This task was part of the story:

  • I want to know how to bet in the long term.

A very trivial task especially with NumPy. Far into the distant future or in theory infinity, the state of our Markov chain system will not change anymore. This is also called a steady state. The stochasic matrix A we calculated last time applied to the steady state, will yield the same state x. Using mathematical notation:

Ax = x

Another way to look at this is as the eigenvector for eigenvalue 1.

1. Smoothing

Last time we counted the number of occurrences for each state transition in our model. This gave us a bit skewed results, because in our sample a Flat or no change situation never occurred. In real life we could have a day that the close price does not change, although unlikely for liquid stock markets. One way to deal with 0 occurrences is to apply additive smoothing. The idea is to add a certain constant to the number of occurrences we find, getting rid of zeroes. Of course, we will have to normalize the probabilites afterwards. Two lines have to change due to the smoothing process. First, change this line

   N = len(start_indices)

to

   N = len(start_indices) + k * NDIM

where k is an integer smoothing constant and NDIM is the number of states, in our case 3. Second, update the line

      SM[i][j] = occurrences/float(N)

to

      SM[i][j] = (occurrences + k)/float(N)

The stochastic matrix for k=1 becomes

[[ 0.47826087  0.00869565  0.51304348]
 [ 0.33333333  0.33333333  0.33333333]
 [ 0.41134752  0.0070922   0.58156028]]

2. Eigenvalues and eigenvectors

To get the eigenvalues and eigenvectors we will need the numpy linalg module and the eig function.

eig_out = numpy.linalg.eig(SM)
print eig_out

The eig function returns an array containing the eigenvalues and an array containing the eigenvectors.

(array([ 1.        ,  0.06739662,  0.32575786]), array([[ 0.57735027,  0.7670805 ,  0.0082198 ],
       [ 0.57735027, -0.19564812, -0.99986103],
       [ 0.57735027, -0.61099044,  0.01450345]]))

3. Selecting the eigenvector for eigenvalue 1

Currently we are only interested in the eigenvector for eigenvalue 1. In reality the eigenvalue might not be exactly 1, so we should build in a margin for error. We can find the index for eigenvalue between 0.9 and 1.1 as follows

idx_vec = numpy.where(numpy.abs(eig_out[0] - 1) < 0.1)
print "Index eigenvalue 1", idx_vec

We get index 0 as expected

Index eigenvalue 1 (array([0]),)

Select the steady state vector

x = eig_out[1][:,idx_vec].flatten()
print "Steady state vector", x

The steady state vector

Steady state vector [ 0.57735027  0.57735027  0.57735027]

4. Check

The check is simple – just multiply the stochastic matrix and the steady state vector we got.

print "Check", numpy.dot(SM, x)

Seems like the result is correct. I will leave it up to you to decide whether it is meaningful or not. Task resolved.

Check [ 0.57735027  0.57735027  0.57735027]

Here is the code in its entirety with imports and all.

#!/usr/bin/env python
 
from matplotlib.finance import quotes_historical_yahoo
from datetime import date
import numpy
import sys
 
today = date.today()
start = (today.year - 1, today.month, today.day)
 
quotes = quotes_historical_yahoo(sys.argv[1], start, today)
close =  [q[4] for q in quotes]
 
states = numpy.sign(numpy.diff(close))
 
NDIM = 3
SM = numpy.zeros((NDIM, NDIM))
 
signs = [-1, 0, 1]
k = int(sys.argv[2])
 
for i in xrange(len(signs)):
   #we start the transition from the state with the specified sign
   start_indices = numpy.where(states[:-1] == signs[i])[0]
 
   N = len(start_indices) + k * NDIM
 
   # skip since there are no transitions possible
   if N == 0:
      continue
 
   #find the values of states at the end positions
   end_values = states[start_indices + 1]
 
   for j in xrange(len(signs)):
      # number of occurrences of this transition 
      occurrences = len(end_values[end_values == signs[j]])
      SM[i][j] = (occurrences + k)/float(N)
 
print SM
eig_out = numpy.linalg.eig(SM)
print eig_out
 
idx_vec = numpy.where(numpy.abs(eig_out[0] - 1) < 0.1)
print "Index eigenvalue 1", idx_vec
 
x = eig_out[1][:,idx_vec].flatten()
print "Steady state vector", x
print "Check", numpy.dot(SM, x)

Have a go

Let’s put the Product Owner hat on. Possible improvement stories I can think of:

  • Fine tune the smoothing constant.
  • Introduce more states.
  • Use different parameters, for instance, option price or volume.
  • Try out different stocks, stock indices or a combination of stocks.
  • Extend to different time periods instead of days.
  • Make some unit tests.

I am looking forward to hearing about your improvements.

 

If you liked this post and are interested in NumPy check out NumPy Beginner’s Guide by yours truly. I would like to thank Mike Driscoll for his book review on the Mouse vs Python blog and on Amazon.com I will be back next week with your Christmas present, which will remain a surprise for now.

Share
Posted in programming | Tagged , | 2 Comments

Stochastic matrix of the FUD states

This entry is part 7 of 17 in the series Numpy Strategies

Numpy Strategies 0.1.2

So we are now in Sprint 12 of Project “NumPy Strategies”. Last week you finished the task of determining states and defining a Markov chain model. This took you ten minutes even though the estimate was 2 days. Hey, that’s the power of NumPy! The rest of the time you spent playing computer games/pool/pinball or reading your favorite book NumPy Beginner’s Guide.

Pop Quiz

Let’s see whether you remember what we decided the states should be:

  • flat F, up U, bottom B, average A, rally R
  • flat F, up U, down D
  • None of the above.
  • This is a trick question!


The next task is:

  • Create the stochastic matrix with transition probabilities

We will estimate this task to 2 days again for obvious reasons.This task can be split into several subtasks, but these are of course not estimated.

1. Initialize the stochastic matrix to 0 values

We have 3 possible start states and 3 possible end states for each transition. For instance, if we start from a U state, we could switch to:

  • U again
  • F
  • D

Initialize the stochastic matrix with the NumPy zeros function.

1
SM = numpy.zeros((3, 3))

2. Create a list containing the signs

This is just a normal Python list.

1
signs = [-1, 0, 1]

3. For each sign select the corresponding start state indices

Now the code becomes a bit messy. We will have to use actual loops! Maybe a better solution will occur to me one day. We will loop over the signs and select the start state indices corresponding to each sign. Select the indices with the NumPy where function.

1
2
3
for i in xrange(len(signs)):
   #we start the transition from the state with the specified sign
   start_indices = numpy.where(states[:-1] == signs[i])[0]

4. Continue to the next iteration if no start states are found

This is just straightforward Python code.

1
2
3
4
5
   N = len(start_indices)
 
   # skip since there are no transitions possible
   if N == 0:
      continue

5. Compute the end state values

The end state indices in our simple model can be found by just getting the next available position.

1
2
   #find the values of states at the end positions
   end_values = states[start_indices + 1]

6. Calculate the transition probabilities

We can now count the number of occurrences of each transition. Dividing by the total number of transitions for a given start state gives us the transition probabilities for our stochastic matrix. This is not the best method by the way, since it could be overfitting.

1
2
3
4
5
6
   for j in xrange(len(signs)):
      # number of occurrences of this transition 
      occurrences = len(end_values[end_values == signs[j]])
      SM[i][j] = occurrences/float(N)
 
print SM

The result for the stochastic matrix is:

1
2
3
[[ 0.47787611  0.          0.52212389]
 [ 0.          0.          0.        ]
 [ 0.42753623  0.          0.57246377]]

As you can see the transitions involving the flat no change state have 0 probability, while the other transitions have a probability close to 50%. This is I guess what we would have expected.


If you liked this post and are interested in NumPy check out NumPy Beginner’s Guide by yours truly. Thanks goes to David W. Lambert for his recent review on Amazon.com and contribution to the unofficial errata. As far as I know there are still 3 reviews in the pipeline for December. One of them was announced on The Glowing Python blog. This announcement also contains a review of the free sample chapter. I will be back next week with the steady state vector task.

Share
Posted in programming | Tagged , , | Leave a comment

Secret Transitions of a Markov Chain

This entry is part 5 of 17 in the series Numpy Strategies

Numpy Strategies 0.1.1

Imagine that one day your most important client/Product Manager/Product Owner/Other walks into your room with the following User Story:

  • I want to make huge profits on the stock market with Markov chains

You think a few seconds and say: “We can implement this easily with NumPy.” You split the User Story in Tasks, the first task being determining state transitions and defining the Markov chain model.

A Markov chain is a system that has at least two states. The system switches at random between these states. I would like to define a Markov chain for a stock – AAPL (disclaimer I own AAPL shares). Let’s say that we have the states flat F, up U and down D. We can determine the states based on end of day close prices.

1. Obtain 1 year of data

Now we need to obtain the data. One way we can do this is with Matplotlib. This is also mentioned in NumPy Beginner’s Guide. We will retrieve the data going back 1 year. Here is the code to do this:

1
2
3
4
today = date.today()
start = (today.year - 1, today.month, today.day)
 
quotes = quotes_historical_yahoo('AAPL', start, today)

2. Select the close price

We now have historical data from Yahoo Finance. The data is represented as a list of tuples, but we are only interested in the close price. We can select the close prices as follows.

1
2
close =  [q[4] for q in quotes]
print len(close)

The close price is the fifth number in each tuple. We should have a list of about 253 close prices now.

3. Determine the states

Finally, we can determine the states by subtracting price of sequential days with the NumPy diff function. The state is then given by the sign of the difference. The NumPy sign function returns -1 for a negative, 1 for a positive number or 0 otherwise.

1
states = numpy.sign(numpy.diff(close))

The nice thing about this NumPy code, is that there were very few for loops. I am willing to bet that it is much faster than equivalent “normal” Python code, so it would be nice to measure the difference. Let’s leave this as an exercise for the reader.

Next time we will compute the transition probabilities for the various states. We will need these numbers to do fancy things with the stochastic matrix and steady state vector.


If you liked this post and are interested in NumPy check out NumPy Beginner’s Guide by yours truly. Last time I checked it was on the bestsellers list of Packt Publishing. This week a review of the book by Marcel Caraciolo generated a lot of buzz on the Internet. Please show your support for this review. I will be back next week with the continuation of the Markov chains story.

Share
Posted in programming | Tagged , | Leave a comment

6 Great Software Development Books I Own

Last week I showed you a stack of books.


stack
They are all great books that roughly fall in the software development category. I would like to tell you something about them. Some of them I have read many times cover to cover. One of them I actually wrote myself.

1. Introduction to Algorithms

This book is like an encyclopedia of algorithms. The algorithms are presented with pseudo code so it doesn’t matter what your favorite programming language is. A very rigorous mathematical approach is used for the analysis of for instance performance.

2. Groovy in Action

Groovy is a new programming language, that is based on Java, but has optional dynamic typing. Groovy also borrows features from Python and Ruby. The examples in this book appealed most to me. Even if, after reading this book as a Java developer, you still want to stick with Java, you would have learned just as much about Java as from any Java book. Groovy is after all very similar to Java.

3. Vi Improved

If you have read my blogs from the very beginning you would know that I am a Vim fan. Even when I write code in Eclipse I try to do it the vi(m) way as much as possible. I don’t recommend reading this book in one go. Rather I suggest reading a bit and then trying out what you read.

4. JUnit Recipes

JUnit is the most popular unit testing framework for Java. JUnit Recipes gives you tons of useful unit testing tips. This book is now outdated, since it covers an older version of JUnit – the one without annotations. Still I learned a lot of basic principles from it.

5. Sed & awk

Sed and awk are Unix power tools. Actually Awk is more of a programming language. This book is a good tutorial on both tools. Apparently it is one of the most popular books on the subject.

6. NumPy Beginner’s Guide

frontcover Finally, it is time to talk about my book NumPy Beginner’s Guide. The first and only book for beginners about NumPy. NumPy Beginner’s Guide is an action-packed guide for the easy-to-use, high performance, Python based free open source NumPy mathematical library using real-world examples. The book will teach you how to analyze large data sets with statistical functions and execute complex linear algebra and mathematical computations.

This week a new review has come to my attention from Stefan Scherfke – one of the technical reviewers of NumPy Beginner’s Guide. Also a few people declared online their intention to review the book – Doug Finke and MousePython. If you are interested in reviewing NumPy Beginner’s Guide in return for a free copy have a look at this Python forum post.

Next week I am planning to write a small NumPy example concerning Markov chains. I am looking forward to your visit next week.

Share
Posted in books, programming | Tagged , | Leave a comment

NumPy Beginner’s Guide Announcement

The long awaited NumPy Beginner’s Guide from Packt Publishing is now available in the stores. The reason that I am announcing it here is of course, that I wrote it myself. I just received print copies of the book and I must say it is one of the most beautiful books I have held in my hands.

stack frontcover samplepage

About the Book

The book is about NumPy and is aimed at people who are interested in learning about NumPy and are able to program with Python. It is a guide filled with practical examples and intentionally low on theory. The examples follow the unique Time For Action tutorial format.

You will learn about:

  • Installing NumPy
  • NumPy arrays, matrices and universal functions
  • NumPy modules
  • Plotting mathematical NumPy results with Matplotlib
  • Integration with Scipy, a high level Python scientific computing framework built on top of NumPy

Table of Contents

You can find the complete table of contents on the Packt Publishing website. Please notice how many Time For Action examples there are in this book. They make up the majority of the pages. Here is the list of chapters:

  • Chapter 1: NumPy Quick Start
  • Chapter 2: Beginning with NumPy Fundamentals
  • Chapter 3: Get into Terms with Commonly Used Functions
  • Chapter 4: Convenience Functions for Your Convenience
  • Chapter 5: Working with Matrices and ufuncs
  • Chapter 6: Move Further with NumPy Modules
  • Chapter 7: Peeking Into Special Routines
  • Chapter 8: Assure Quality with Testing
  • Chapter 9: Plotting with Matplotlib
  • Chapter 10: When NumPy is Not Enough: SciPy and Beyond

Buy the Book

I got a sample of links from the publisher that link to some of the online shops where you can buy the book:

If you want to share another link to the book feel free to post it in the comments.

Reviews

I found a mention of the book by Dr. Seth Brown one of the technical reviewers of the book. Let me know, if you want to write a review (so I can link to your review) or reply to this forum thread. The latter guarantees you a free copy of the book.

Acknowledgments

Last but not least, I would like to thank the technical reviewers and the people at Packt Publishing for making this masterpiece possible.

Share
Posted in books, programming | Tagged , , | 2 Comments

Stackrumban Scrumban StackOverflow style

This entry is part 2 of 2 in the series Average Price Script

A thought experiment and Average Price Script 0.0.2

This is a thought experiment, so I have no idea whether it will make sense eventually. Scrumban is a cross between Scrum and Kanban. It has daily meetings but no fixed length sprints. The flow is continuous.

StackOverflow style

This seems very boring to me. Let’s add a point system like the one from StackOverflow. Team members can then vote, downvote or accept tasks and associated work. The Hudson build game is based on a similar idea, but it uses automatic scoring. Of course, we want to go further than that and have gradual unlocking of privileges and all sorts of badges.

Average Price Script 0.0.2

I was planning to write a long story about StackOverflow and Stackrumban, but now I decided to await how it all works out. If you are going to make more out of it, remember that I have the copyright! Instead I give the new version of Average Price Script 0.0.1. Now in Python with standard deviation. I used Numpy for the statistics.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while True:
   req = urllib2.Request('http://finance.google.com/finance/info?client=ig&q=' + sys.argv[1])
   req.add_header('User-agent', 'Mozilla/5.0')
   response = urllib2.urlopen(req)
   page = response.read()
   m = re.search('l_cur" : "(.*)"', page)
   prices.append( float( m.group(1) ) )
   avg = mean( prices )
   sigma = std( prices )
 
   devFactor = float(sys.argv[3])
   min = avg - devFactor * sigma
   max = avg + devFactor * sigma
   timestr = strftime("%d %b %H:%M:%S", gmtime())
 
   print timestr, "Average", avg, numShares(avg), "-Std", min, numShares(min), "+Std", max, numShares(max)
   time.sleep(int(sys.argv[2]))

Random links of interest

Share
Posted in programming | Tagged | Leave a comment

Average Price Script 0.0.1

This entry is part 1 of 2 in the series Average Price Script

So I made a small Perl script again. The script polls data from Google Finance and calculates the average price for a given symbol. The first parameter of the script is the Google Finance symbol that starts with the name of the exchange followed by a colon like ‘NYSE:IBM’. The script expects an optional second parameter an integer number indicating the poll interval, 1 by default. Data is retrieved with curl. The response is in the JSON format. I get the current price with a regex from the response. All the prices are stored in an array and averaged. I also do some rudimentary logging.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/perl
 
# This script polls data from Google Finance and calculates the average price for a given symbol.
#
# Parameters:
#  symbol         The Google Finance symbol like 'NYSE:IBM'.
#  secondsSleep   Integer number indicating the poll interval, 1 by default.
#
$symbol = $ARGV[0];
print "$symbol\n";
 
while(1) {
   $data=`curl -s "http://finance.google.com/finance/info?client=ig&q=$symbol"`;
   $data =~ m/l_cur" : "(.*)"/;
   $td=`date +'%Y%m%d %H:%M - '`;
   push(@prices, $1);
   $num = scalar @prices;
   $sum = 0;
 
   for( $i = 0; $i < $num; $i++) {
      $sum += $prices[$i];
   }
 
   $average = $sum / $num;
   print "$num elements, average $average\n";
   print "$1 $td";
   sleep $ARGV[1];
}

Possible improvements

Here is a list of improvements I have been thinking about.

  • Use a proper JSON library.
  • Calculate standard deviation as well.
  • Calculate a time weighted average, where recent values have a higher weight.
  • Improve logging.

Random links of interest

Share
Posted in programming | Tagged | Leave a comment

What is the optimal holding period for shares?

This entry is part of 17 in the series Numpy Strategies

Numpy Strategies 0.1.0

Happy New Year! So I was collecting evidence for my prediction of the gold bubble bursting early in 2011 and I found this article. Very short summary – 14 June 2011. What do I think? I think this is completeley incorrect. They are off by at least two days.

The plan for today is:

  1. Define a volatility band for the log of stock prices and mean reverting strategy based on dips below the band.
  2. Optimization for the holding period of shares.
  3. Profit and champagne(optional).

Numpy 4 portfolio closed

The Numpy 4 portfolio was a nice little stable portfolio. I think that it had to do with the Jarque-Bera test prefiltering. Numpy 4 seemed to select mainly energy ETFs. I also did some experimentation with trailing stops. This also might account for its success.

numpy4Chart perfNumpy4

Here is a summary of the closed Numpy portfolios until now.

Stops update

The Numpy 5 portfolio had some startup issues, but this week was pretty OK.

The band

The first step in defining the band is transforming to the logarithm of the stock price. Next, I find the local minima’s. For now, I define the local minimum as the point with the lowest value of the set containing this point and 5 earlier and 5 later points.

1
2
3
4
5
6
7
8
9
10
def locMins(arr, period=1):
   mins = []
 
   for i in range(period,len(arr) - period):
      themin = min(arr[i - period : i + period])
 
      if arr[i] <= themin:
         mins.append(i)
 
   return mins

Then, I fit a line through these minima. If the fit fails, Numpy returns an empty residuals array – so I check for that.

1
2
3
4
5
6
7
8
9
10
11
12
   logc = log(c[: int(argv[1]) ])
   mins = locMins(logc, 5)
 
   y = []
 
   for m in mins:
      y.append( logc[m] )
 
   (a,b,residuals) = fitline(mins, y)
 
   if len(residuals) == 0:
      continue

The band is formed by adding and subtracting the standard deviation of log of the close price with respect to the regression line. I also check whether a certain percentage of the historical prices falls within this band.

1
2
3
4
5
6
7
8
9
def within_band_ratio(arr, a, b, err):
   count = 0
 
   for i in range( len(arr) ):
      if arr[i] <= (a * i + b + err):
         if arr[i] >= (a * i + b - err):
            count += 1
 
   return count / float( len(arr) )

This is what the histogram of the “within band ratio” looks like. Seems to be skewed the right way, don’t you agree?

wbrhist

Now it’s time for the mean reverting strategy that selects dips below the band.

1
2
3
4
5
6
7
8
9
10
   STD = std(logc)
 
   last = log( c[ int(argv[1] ) + 1 ] )
   if last >= ( a * len(logc) + b - STD):
      continue
 
   wbr = within_band_ratio(logc, a, b, STD)
 
   if wbr < float( argv[2] ):
      continue

Optimal holding period

Common sense tells us that the optimal holding period would be less than a day. However, sometimes we don’t have enough data for that or whatever. The best choice is of course associated with the largest return, so I try to estimate this. O yeah, I did something with time averaging, ignore it for now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
...
def expected_return( p, period ):
   indices = arange( 0, len(p), period )
   q = take( p, indices )
   r = get_returns( q )
 
   return geomean( r )
 
o,c = loadtxt(path( argv[ 1 ] + '.csv' ), delimiter=',', usecols=(3,6), unpack=True, converters={3: float_converter }) 
 
ers = []
twers = []
maxEr = expected_return( c, 1 ) 
ers.append( maxEr )
 
maxTwer = expected_return( c, 1 )
twers.append( maxTwer )
optPeriod = 1
optTWPeriod = 1
 
for i in range(2, 30):
   er = expected_return( c, i)
   twer = er / i
 
   ers.append( er )
   twers.append( twer )
 
   if er > maxEr:
      maxEr = er
      optPeriod = i
 
   if twer > maxTwer:
      maxTwer = twer
      optTWPeriod = i
...

Here are the plots of holding periods and expected returns.

wcnHold scmfoHold mbbHold

This spreadsheet shows the optimal holding periods.

A Vogon Portfolio

Resistance is useless

Prostetnic Vogon Jetzt captain of the yellow constructor ship Grossebanana was feeling a bit sorry for himself. Jetzt denied his crew their shore leave, but that was not enough to cheer him up. Nobody appreciated his poetry. Not even the two hitchhikers, they had just caught.

See, see the sky
Marvel at its big pink depths.
Tell me, do you
Wonder why the goat ignores you?
Why its foobly stare
makes you feel sleepy.
I can tell you, it is
Worried by your shazbaz facial growth
That looks like
A milk.
What's more, it knows
Your fudge potting shed
Smells of frog.
Everything under the big sky
Asks why, why do you even bother?
You only charm cheeses.

It wasn’t that bad, was it now? The other problem was that the Prostetnic and the whole Vogon Construction Fleet would be out of work soon. You see, the Vogons were in the business of planet demolition. In the past tearing down planets was necessary to make space for hyperspace travel. But now, with the invention of a new type of spaceship, this was no longer needed. Jetzt was good at two things. Shouting and planet demolition. He had a brilliant career first as a space guard, Junior Shouting Officer, Just Shouting Officer, Senior Shouting Officer, Super Senior Shouting Officer and eventually captain of Grossebanana.

Jetzt did something unusual. He asked the hitchhikers for advice. First, they advised him jokingly to become a pirate, which provoked half hour of the Vogon shouting. When the captain calmed down, the freeloaders asked him whether he had considered trading. That was a fine profession in which shouting was encouraged.

Yes, the Prostetnic thought to himself, that was not such a bad idea. The Vogon’s victims encouraged by the sudden silence started talking about some kind of a trading strategy, that was discovered on an ancient planet, known throughout the Galaxy as being “mostly harmless”. Unfortunately, soon after the strategy became popular, the planet was demolished by the Vogons. A few hours of shouting later the hitchhikers and Jetzt created the following portfolio:


numpy10

The captain pulled on the yellow fish stuck in his ear and shouted.

Resistance is useless!

THE END

Random links of general interest

If you liked this post and are interested in NumPy check out NumPy Beginner’s Guide by yours truly.

Share
Posted in programming | Tagged , , | Leave a comment