我有一个算法,把股市行情数据转换成烛台。
所以我想让你读一下代码,并给我一些建议,让它更快
股票价格表
stock_price = [ 5, 5.1, 5, 4.9 , ... ]
timestamps = [ 1534339504.36133 , 1534339704.36133, 1534339804.36133, 1534340504.36133, ... ]
您会注意到采样率是可变的,有时可能是几秒,有时可能是几分钟。输入列表通过增加时间戳进行排序。
所以我给了一些我想计算的蜡烛。每支蜡烛的持续时间为T。如果我要求10支蜡烛的持续时间为5分钟,我没有足够的时间戳,第一支蜡烛将是NAN。另一方面,如果我有大量的时间戳从过去几周,只有最后的样本将被考虑到计算最后10蜡烛,其余的将是忽略。
通常,它们是指UTC,我认为列表中的最后一个元素是最后一支蜡烛的收盘价和时间
所以为了把这两个列表转换成烛光图,我做了如下的工作
# time_interval is the size of the candle: 1, 5, 10... minutes, hours, etc
# nb_candles is the number of candles that I want to extract ( for example the last 5 candles )
def convert_samples_to_candles( stock_price , times , time_interval , nb_candles=-1 ):
#If no data return NaNs
if( len(stock_price) == 0 or len(times) == 0 ):
NO_RESPONSE = [np.NaN]
return NO_RESPONSE, NO_RESPONSE, NO_RESPONSE, NO_RESPONSE, NO_RESPONSE
last_time = times[-1]
last_val = stock_price[-1]
#if nb_candles is not specified compute all the candles
if( nb_candles==-1 ):
nb_candles = int((last_time - times[0])/time_interval) + 1
candles_open = [np.NaN]*nb_candles
candles_close = [np.NaN]*nb_candles
candles_high = [np.NaN]*nb_candles
candles_low = [np.NaN]*nb_candles
candles_time = [np.NaN]*nb_candles
k=1
last_candle = -1
#Initialize the last candles with the last value
candles_open[-1] = last_val
candles_close[-1] = last_val
candles_high[-1] = last_val
candles_low[-1] = last_val
candles_time[-1] = last_time
#Iterate and fill each candle from the last one to the first one
nb_times = len(times)
while( k < nb_times and times[-1*k] + nb_candles*time_interval > last_time ):
a_last = stock_price[-1*k]
a_timestamp = times[-1*k]
candle_index = (-1*int((last_time - a_timestamp)/time_interval) -1)
if( candle_index > -1 ):
k += 1
continue
if( candle_index < last_candle ):
candles_time[ candle_index ] = a_timestamp
candles_close[ candle_index ] = a_last
candles_high[ candle_index ] = a_last
candles_low[ candle_index ] = a_last
candles_open[ candle_index ] = a_last
last_candle = candle_index
else:
#print candle_index, candles_open
candles_open[ candle_index ] = a_last
if( candles_high[ candle_index ] < a_last ):
candles_high[ candle_index ] = a_last
if( candles_low[ candle_index ] > a_last ):
candles_low[ candle_index ] = a_last
k += 1
return candles_open, candles_close, candles_high, candles_low, candles_time
非常感谢你的时间!