/python/algo_local/Signal.py
Python | 89 lines | 43 code | 18 blank | 28 comment | 11 complexity | 1622abf92df3826bd82cfae426a49505 MD5 | raw file
- import numpy as np
- import pandas
- def make(data_frame, symbols):
- return Signal(data_frame, symbols)
- class Signal(object):
- '''
- Class Signal
- '''
- def __init__(self, data_frame, symbols):
- '''
- Constructor
- '''
- self.data = data_frame
- self.symbols = symbols
- self.signal = []
- def _liquidity(self,window):
- '''
- calculate liquidity within a given window
- return the most liquid stock, set their corresponding position as 1
- '''
- liquidity = np.array([])
- #loop through the symbols
- for symbol in self.symbols:
- volumn = self.data[symbol]["vol"][-window:-1]
- price = self.data[symbol]["cp"][-window:-1]
- liquidity = np.append(liquidity, sum(volumn*price))
- sorted_liquidity = np.sort(liquidity)
- liquidity[liquidity < sorted_liquidity[-6]] = 0
- return liquidity
- def gen_idx(self, window, most_liqd_len, least_liqd_len):
- '''
- return two list of symbols,
- one contains the most liquid stock symbols,
- the other contains the least liquid stock symbols.
- window: the look back window to determin liquidity
- most_liad_len: the number of tops you want
- least_liqd_len: the number of bottoms you want
- '''
- liquidity = self._liquidity(window)
- sort_liquidity = np.sort(liquidity) #sort the liquidity
- dummy_index = np.array(range(0,len(self.symbols))) #get the index of the least liquid stocks
- self.least_liquid = [self.symbols[i] for i in dummy_index[liquidity < sort_liquidity[least_liqd_len]]]
- #get a list of the symbols that are least liquid
-
- self.most_liquid = [self.symbols[i] for i in dummy_index[liquidity > sort_liquidity[- most_liqd_len - 1]]]
- #get a list of the symbols that are most liquid
- def gen_signal(self, window):
- '''
- dummy rule right now
-
- '''
- signal = {};
- most_liquid_index_ts = None
-
- #print self.most_liquid
- #get average direction of the most liquid stock
- for symbol in self.most_liquid:
- if most_liquid_index_ts is None:
- most_liquid_index_ts = self.data[symbol]["cp"][-2* window:-1]
- else:
- most_liquid_index_ts = most_liquid_index_ts + self.data[symbol]["cp"][-2* window:-1]
-
- #calculate z-score
- z_score = (most_liquid_index_ts -pandas.rolling_mean(most_liquid_index_ts,10).shift(1))/pandas.rolling_std(most_liquid_index_ts,10).shift(1)
- if z_score[-1] > 0.1 :
- for symbol in self.least_liquid:
- signal[symbol] = 1.
- elif z_score[-1] < -0.1:
- for symbol in self.least_liquid:
- signal[symbol] = -1.
- vector_signal = np.zeros(len(self.symbols))
-
- for symbol in signal.keys():
-
- vector_signal[self.symbols.index(symbol)] = signal[symbol]
- return vector_signal
-
-
-