ivanidris.
net
NumPy Project Euler Problem 5
Project Euler Problem 5is one of those problems that seem hard, but turn out to be trivial after you
think about them.
In this case it is very important to use the information given to you in the
problem.
This means using the fact that 2520 is the smallest number that can be divided by...
Plus
ivanidris. net NumPy Project Euler Problem 5 Project Euler Problem 5is one of those problems that seem hard, but turn out to be trivial after you think about them. In this case it is very important to use the information given to you in the problem. This means using the fact that 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. We can therefore limit our search to multiples of 2520. 1. Create a divisors array First we will create a divisors array. We only need to divide by the numbers 11 – 20. divisors = numpy. arange(11, 21) 2. Check for 0 remainder Second make sure that all the divisions of a number by the divisors produce a 0 remainder. We can check for that with the NumPy all function. numpy. all((i % divisors) == 0) 3. Test the solution Eventually we will get an answer. We need to check whether this is the correct answer. Use the assert_equal function from the numpy. testing module to confirm the result. numpy
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 18 Fév. 2012
Pages: 1
Lectures: 0
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 6
Project Euler Problem 6 is perfect to demonstrate the power of NumPy.
No loops are required and
only a few lines of code.
1.
Create an array with the first 100 natural numbers
First we will create a NumPy array of the numbers 1 – 100 with the arange function.
2.
Sum the squares of the...
Plus
ivanidris. net NumPy Project Euler Problem 6 Project Euler Problem 6 is perfect to demonstrate the power of NumPy. No loops are required and only a few lines of code. 1. Create an array with the first 100 natural numbers First we will create a NumPy array of the numbers 1 – 100 with the arange function. 2. Sum the squares of the numbers Second we will sum the squares of the numbers with the sum function. sum_squares = numpy. sum(a ** 2) 3. Square the sum of the numbers The NumPy ndarray class has a sum method, that we can use to sum the numbers in our array. After that calculate the square of the sum. square_sum = a. sum() ** 2 Below is the complete solution. import numpy #The sum of the squares of the first ten natural numbers is, #1 ** 2 + 2 ** 2 + . . . + 10 ** 2 = 385 #The square of the sum of the first ten natural numbers is, #(1 + 2 + . . . + 10) ** 2 = 55 ** 2 = 3025 #Hence the difference between the sum of the squares of the first ten natural nu mbers and the square
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 18 Fév. 2012
Pages: 1
Lectures: 0
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 7
Project Euler Problem 7 is about prime numbers.
So I implemented a Sieve of Eratosthenes with
NumPy.
I am not following the algorithm to the letter, but I believe that the result is the same.
1.
Create a list of consecutive integers
The first mandatory step is to create a list of natural...
Plus
ivanidris. net NumPy Project Euler Problem 7 Project Euler Problem 7 is about prime numbers. So I implemented a Sieve of Eratosthenes with NumPy. I am not following the algorithm to the letter, but I believe that the result is the same. 1. Create a list of consecutive integers The first mandatory step is to create a list of natural numbers. NumPy has the arange function for that. 1 a = numpy. arange(i, i + LIM, 2) 2. Sieve out multiples of p Not sure whether this is what Eratosthenes wanted us to do, but it works. Below we are passing a NumPy array and getting rid of all the elements that have a 0 remainder, when divided by p. Below is the entire code for this problem. 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 import numpy LIM = 10 ** 6 N = 10 ** 9 P = 10001 primes = [] p = 2 #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6t #What is the 10 001st prime number? def check_primes(a, p): #2. Sieve out mult
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 18 Fév. 2012
Pages: 1
Lectures: 1
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 1
Project Euler is a website that lists a number of mathematical problems, which are perfect to be
solved with NumPy.
Let’s start the new year with Problem 1.
1.
Call the arange function
Call the arange function in order to store all the integers from 1 to 1000 in an array.
# 1.
Numbers...
Plus
ivanidris. net NumPy Project Euler Problem 1 Project Euler is a website that lists a number of mathematical problems, which are perfect to be solved with NumPy. Let’s start the new year with Problem 1. 1. Call the arange function Call the arange function in order to store all the integers from 1 to 1000 in an array. # 1. Numbers 1 - 1000 a = numpy. arange(1, 1000) 2. Select the multiples of 3 or 5 Select using the [] operator. # 2. Select multiple of 3 or 5 a = a[(a % 3 == 0) | (a % 5 == 0)] print a[:10] This prints as expected [ 3 5 6 9 10 12 15 18 20 21] 3. Sum the array elements Call the sum method on the NumPy array. # 3. Sum the numbers print a. sum() Once again the code below in its entirety. import numpy #Problem 1. #If we list all the natural numbers below 10 that are multiples of 3 or 5, we ge t 3, 5, 6 and 9. #The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. # 1. Numbers 1 - 1000 a = numpy. arange(1, 1000) # 2. Selec
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 2
Lectures: 0
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 3
Project Euler Problem 3 seems almost impossible to crack.
However, using the right algorithm –
Fermat’s factorization method and NumPy, it becomes very easy.
The idea is to factor a number N
into two numbers c and d.
N = c * d = (a + b) (a - b) = a ** 2 - b ** 2
We can apply the...
Plus
ivanidris. net NumPy Project Euler Problem 3 Project Euler Problem 3 seems almost impossible to crack. However, using the right algorithm – Fermat’s factorization method and NumPy, it becomes very easy. The idea is to factor a number N into two numbers c and d. N = c * d = (a + b) (a - b) = a ** 2 - b ** 2 We can apply the factorization recursively, until we get the required prime factors. 1. Create array of trial values The algorithm requires us to try a number of trial values for a. It makes sense to create a NumPy array and eliminate the need for loops. However, you should be careful to not create an array that is too big. On my system an array of a million elements seems to be just the right size. a = numpy. ceil(numpy. sqrt(n)) lim = min(n, LIM) a = numpy. arange(a, a + lim) b2 = a ** 2 - n 2. Get the fractional part of the b array We are now supposed to check whether b is a square. Use the NumPy modf function to get the fractional part of the b array. fractions = nump
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 2
Lectures: 0
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 4
Project Euler Problem 4 is a bit silly.
It’s about palindromic numbers.
I could not find an
appropriate algorithm, so I just tried something out.
It seems to work OK.
1.
Create a 3-digit numbers array
We will create an array to hold 3-digit numbers from 100 to 999 using our favorite...
Plus
ivanidris. net NumPy Project Euler Problem 4 Project Euler Problem 4 is a bit silly. It’s about palindromic numbers. I could not find an appropriate algorithm, so I just tried something out. It seems to work OK. 1. Create a 3-digit numbers array We will create an array to hold 3-digit numbers from 100 to 999 using our favorite NumPy function arange. Check the first and last element of the array with the assert_equal function from the numpy. testing package. a = numpy. arange(100, 1000) numpy. testing. assert_equal(100, a[0]) numpy. testing. assert_equal(999, a[-1]) 2. Create the products array Now we will create an array to hold all the possible products of the elements of the 3-digits array with itself. We can accomplish this with the outer function. The resulting array needs to be flattened with ravel, to be able to easily iterate over it. Call the sort method on the array to make sure the array is properly sorted. After that we can do some sanity checks. numbers = numpy
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 2
Lectures: 0
Téléchargements: 0
ivanidris.
net
Jarque Bera, the CAPM and undervalued
stocks
The Capital Asset Pricing Model ( CAPM ) links the expected return of assets to their risk.
A linear
fit of this relationship gives us the so called Security Market Line ( SML ).
One of the problems
with this model is that it assumes a normal distribution of returns.
The...
Plus
ivanidris. net Jarque Bera, the CAPM and undervalued stocks The Capital Asset Pricing Model ( CAPM ) links the expected return of assets to their risk. A linear fit of this relationship gives us the so called Security Market Line ( SML ). One of the problems with this model is that it assumes a normal distribution of returns. The python scikits. statsmodels. stattools module provides a Jarque Bera normality test, which allows me to select only the stocks which have nearly normal return distribution. Jarque Bera test I check with the Jarque-Bera test for normality. Normality implies predictability. Predictability leads to safety. Safety leads to joy. The code below screens for a certain Jarque Bera test p – value of open, high, low and close prices returns. 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 . . . def get_returns( arr ): beforeLast = len( arr ) - 2 return diff( arr[ : beforeLast] ) / arr[ : beforeLast - 1] def get_pvals
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 2
Lectures: 4
Téléchargements: 0
ivanidris.
net
Portfolio analysis with Pandas for the win
I saw a PyCon presentation about pandas.
Pandas is a data analysis Python library, which works
with timeseries data and handles missing data automatically.
It is based on NumPy and should work
well together with for instance scikits.
statsmodels.
Pandas correlation
A Panda...
Plus
ivanidris. net Portfolio analysis with Pandas for the win I saw a PyCon presentation about pandas. Pandas is a data analysis Python library, which works with timeseries data and handles missing data automatically. It is based on NumPy and should work well together with for instance scikits. statsmodels. Pandas correlation A Panda DataFrame is a matrix and dictionary-like data structure. In fact, it is the central data structure in Pandas and you can apply all kinds of timeseries operations on it. It is quite common to have a look at the correlation matrix of a portfolio. So I did that for a number of CSV files containing end-of-day price data, although one can argue, that it is a bit pointless. First, I created the DataFrame with Pandas for each symbol’s daily returns. Then I joined these on the date. At the end the correlation was printed and plot shown. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 . . . for symbol in symbols: dates,close = loadtxt(fileDir +
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 1
Lectures: 1
Téléchargements: 0
ivanidris.
net
NumPy Project Euler Problem 2
Project Euler Problem 2 is definitely harder than Problem 1.
This one requires reading the Fibonacci
numbers Wikipedia article.
I read that the Project Euler problems are some sort of katas.
Katas are what martial artist call
exercises, preparing you for real-life fighting situations....
Plus
ivanidris. net NumPy Project Euler Problem 2 Project Euler Problem 2 is definitely harder than Problem 1. This one requires reading the Fibonacci numbers Wikipedia article. I read that the Project Euler problems are some sort of katas. Katas are what martial artist call exercises, preparing you for real-life fighting situations. For instance, imagine that your house is on fire and that your family is surrounded by heavily armed thugs. What do you do? In this case your secret weapon is NumPy, which is like the Dim Mak death touch. If you master that like me, then you don’t even need to bother with katas. 1. Calculate the golden ratio When the bad ninja guys are walking towards you, the first thing to do, is calculate the golden ratio, also called the golden section. This part of the kata is called Moro Ashi Dachi. 1 2 phi = (1 + numpy. sqrt(5))/2 print "Phi", phi This prints the golden mean. 2. Find the index below 4 million Next in the kata we need to find the index below 4
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 27 Jan. 2012
Pages: 3
Lectures: 0
Téléchargements: 0
What is the optimal holding period for shares?
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).
The band
The first step in defining the band is transforming...
Plus
What is the optimal holding period for shares? 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). 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,residua
Moins
Par Ivan Idris
Document Adobe PDF
Publiée le 7 Jan. 2012
Pages: 3
Lectures: 0
Téléchargements: 0