Thursday, September 29, 2016

Fourier transform based trading strategy

The Fourier Transform based Python code is based on the Basic Trading Strategy running on Quantopian framework.

Starting cash: $10,000, tested from 8/1/15 to 8/31/16

The algorithm creates a buy and a sell threshold. The thresholds are functions of past performance. The idea of using FT is that the high frequency noise can be filtered out and the trend can be obtained. The ratio is the mean of a few recent prices divided by the mean of more prices. In the special case if you use 1 price, the mean is itself.

from scipy.fftpack import fft
import numpy
from scipy.fftpack import ifft

def initialize(context):
    
    context.security = sid(43721) # SCTY
    N = 20
    prices = numpy.asarray(history(N, '1d', 'price')) 
    # Turn off high frequencies
    wn = 5
    y = fft(numpy.transpose(prices)[0])
    print(numpy.transpose(prices))
    y[wn:-wn] = 0
   
    x1rec = ifft(y).real
    current_rec = numpy.mean(x1rec[:15])
    average_rec = numpy.mean(x1rec) # average of N elements
    ratio = current_rec/average_rec
    
    buy_threshold = 0.99 # Ratio threshold at which to buy
    close_threshold = 1.0  # Ratio threshold at which to close buy position
   
    current_price = data[context.security].price    
    cash = context.portfolio.cash

    if ratio < buy_threshold and cash > current_price:
        
        # Need to know how many shares we can buy
        number_of_shares = int(cash/current_price)
        
        # Place the buy order (positive means buy, negative means sell)
        order(context.security, +number_of_shares)
        
    elif ratio > close_threshold:
        
        # Sell all of our shares by setting the target position to zero
        order_target(context.security, 0)
    
    # Plot the stock's price
    record(stock_price=data[context.security].price)