def graficar(VALORES_PROCESAR,directorio_base):	
	data = [None,None,None,None,None,None,None,None,None]
	fname = os.path.join(os.path.dirname(__file__),FILENAME)
	with open(fname, 'rb') as csvfile:
		spamreader = csv.reader(csvfile, delimiter=';')
		tipo_valor_1 = None
		tipo_valor_2 = None
		for row in spamreader:
			valor,lotes,margen,spread,tp_spread,tipo,codigo,nombre,descripcion = row
			if valor == VALORES_PROCESAR[0]: 
				datos = fd.cargar_valores(valor,PERIODO)

				data[1]=datos['open'][-TEMPORALIDAD:]
				data[2]=datos['close'][-TEMPORALIDAD:]
				data[3]=datos['high'][-TEMPORALIDAD:]
				data[4]=datos['low'][-TEMPORALIDAD:]
				data[0]=datos['fecha'][-TEMPORALIDAD:]
				
				tipo_valor_1 = tipo
				
			elif valor == VALORES_PROCESAR[1]: 
				datos = fd.cargar_valores(valor,PERIODO)
				
				data[5]=datos['open'][-TEMPORALIDAD:]
				data[6]=datos['close'][-TEMPORALIDAD:]
				data[7]=datos['high'][-TEMPORALIDAD:]
				data[8]=datos['low'][-TEMPORALIDAD:]
				
				tipo_valor_2 = tipo
				

	data_correlacion = []
	data_fecha = []
	for x in range(0,len(data[0])):
		a = [data[1][x]/data[5][x], data[2][x]/data[6][x], data[3][x]/data[7][x], data[4][x]/data[8][x]]
		data_correlacion.append(a)
		data_fecha.append(data[0][x])

	
	data_cierre = []
	for v in data_correlacion:
		data_cierre.append(v[1])
	
	rsi14 = fb.calcular_rsi(14, data_cierre)
	macd, macd_signal, macd_histograma = fb.get_macd(data_cierre,12,26,9) 
	estocastico_sk_14, estocastico_sd_14 = fb.calcular_estocastico(data_cierre, data_cierre, data_cierre, 20, 3)
	
	ema9 = fb.get_ema_periodo(12,data_cierre)
	ema20 = fb.get_ema_periodo(50,data_cierre)
	ema50 = fb.get_ema_periodo(100,data_cierre)

	TITULO = "{}-{}".format(VALORES_PROCESAR[0],VALORES_PROCESAR[1])
	correlacion(TITULO,data_fecha,data_correlacion,ema9,ema20,ema50,rsi14,macd, macd_signal, macd_histograma,estocastico_sk_14,estocastico_sd_14,directorio_base,"{}-{}".format(tipo_valor_1,tipo_valor_2),TEMPORALIDAD)
Exemple #2
0
def combinarValores(DIRECTORIO_BASE, VALORES, TEMPORALIDAD):

    fname1, fname2 = VALORES
    filename1 = os.path.join(DIRECTORIO_BASE, 'csv', TEMPORALIDAD,
                             fname1 + '.csv')
    filename2 = os.path.join(DIRECTORIO_BASE, 'csv', TEMPORALIDAD,
                             fname2 + '.csv')

    dirFilenameResult = os.path.join(DIRECTORIO_BASE, 'csv', 'pares')
    if not os.path.exists(dirFilenameResult):
        os.makedirs(dirFilenameResult)
        print("creando directorio.... {}".format(dirFilenameResult))

    dirFilenameResult = os.path.join(DIRECTORIO_BASE, 'csv', 'pares',
                                     TEMPORALIDAD)
    if not os.path.exists(dirFilenameResult):
        os.makedirs(dirFilenameResult)
        print("creando directorio.... {}".format(dirFilenameResult))

    filename3 = os.path.join(DIRECTORIO_BASE, 'csv', 'pares', TEMPORALIDAD,
                             "{}-{}.csv".format(fname1, fname2))

    file_1 = pd.read_csv(filename1,
                         index_col=0,
                         parse_dates=True,
                         infer_datetime_format=True,
                         sep=";")

    file_2 = pd.read_csv(filename2,
                         index_col=0,
                         parse_dates=True,
                         infer_datetime_format=True,
                         sep=";")

    fecha = []
    apertura = []
    cierre = []
    high = []
    low = []

    for f in file_1.index:

        y = file_2[(file_2.index == f)]
        if len(y) == 0: continue

        a = file_2['apertura'][(file_2.index == f)]
        b = file_2['cierre'][(file_2.index == f)]
        c = file_2['high'][(file_2.index == f)]
        d = file_2['low'][(file_2.index == f)]

        fecha.append(f)
        apertura.append(file_1['apertura'][f] / a.values[0])
        cierre.append(file_1['cierre'][f] / b.values[0])
        high.append(file_1['high'][f] / c.values[0])
        low.append(file_1['low'][f] / d.values[0])

        # print (f, file_1['cierre'][f])

        # print(a.values[0])
        # sys.exit()

    macd, macd_signal, macd_histograma = fb.get_macd(cierre, 12, 26, 9)
    rsi14 = fb.calcular_rsi(14, cierre)
    rsi50 = fb.calcular_rsi(50, cierre)

    estocastico_sk_14, estocastico_sd_14 = fb.calcular_estocastico(
        cierre, high, low, 14, 3)
    estocastico_sk_50, estocastico_sd_50 = fb.calcular_estocastico(
        cierre, high, low, 20, 3)

    #calcula emas de 5 a 200
    sma5 = fb.get_sma_periodo(5, cierre)
    ema5 = fb.get_ema_periodo(5, cierre)

    sma20 = fb.get_sma_periodo(20, cierre)
    ema20 = fb.get_ema_periodo(20, cierre)

    sma200 = fb.get_sma_periodo(200, cierre)
    ema200 = fb.get_ema_periodo(200, cierre)

    sma100 = fb.get_sma_periodo(100, cierre)
    ema100 = fb.get_ema_periodo(100, cierre)

    sma50 = fb.get_sma_periodo(50, cierre)
    ema50 = fb.get_ema_periodo(50, cierre)

    sma400 = fb.get_sma_periodo(400, cierre)
    ema400 = fb.get_ema_periodo(400, cierre)

    lecturas = len(cierre)
    with open(filename3, 'wb') as csvfile:
        spamwriter = csv.writer(csvfile,
                                delimiter=';',
                                quotechar='|',
                                quoting=csv.QUOTE_MINIMAL)
        dataset = [
            'fecha', 'apertura', 'cierre', 'high', 'low', 'macd',
            'macd_signal', 'macd_histograma', 'rsi14', 'rsi50', 'esk14',
            'esd14', 'esk50', 'esd50', 'sma[5]', 'ema[5]', 'sma[20]',
            'ema[20]', 'sma[50]', 'ema[50]', 'sma[100]', 'ema[100]',
            'sma[200]', 'ema[200]', 'sma[400]', 'ema[400]'
        ]
        spamwriter.writerow(dataset)

        for x in range(0, lecturas):
            dataset = [
                fecha[x], apertura[x], cierre[x], high[x], low[x], macd[x],
                macd_signal[x], macd_histograma[x], rsi14[x], rsi50[x],
                estocastico_sk_14[x], estocastico_sd_14[x],
                estocastico_sk_50[x], estocastico_sd_50[x], sma5[x], ema5[x],
                sma20[x], ema20[x], sma50[x], ema50[x], sma100[x], ema100[x],
                sma200[x], ema200[x], sma400[x], ema400[x]
            ]
            spamwriter.writerow(dataset)

    correlacion(VALORES, DIRECTORIO_BASE, TEMPORALIDAD, filename3)
Exemple #3
0
date1 = "2017-6-1"
date2 = "2017-12-31"

# every monday
mondays = WeekdayLocator(MONDAY)
daysFmt = DateFormatter("%d %b %y")

quotes = pd.read_csv('yahoofinance-GOOG-20040819-20180120.csv',
                     index_col=0,
                     parse_dates=True,
                     infer_datetime_format=True)
''' generamos la ema. recordar que los valores pueden
ser 0 y daria problemas en el grafico.
por eso la generamos aqui.'''
ema50 = fb.get_ema_periodo(50, quotes['Close'])

# select desired range of dates
quotes = quotes[(quotes.index >= date1) & (quotes.index <= date2)]
''' ajustamos los valores de la media a los valores del cierre'''
l = len(quotes['Close'])
ema50 = ema50[-l:]

fig, ax = plt.subplots(figsize=(24, 12))

plot_day_summary_oclh(ax,
                      zip(date2num(quotes.index.to_pydatetime()),
                          quotes['Open'], quotes['Close'], quotes['Low'],
                          quotes['High']),
                      ticksize=3)
Exemple #4
0
def procesar_valor(VALOR,CODIGO,RESOLUCION,DIRECTORIO_BASE):
	
	fname = VALOR 
	print ("procesando valor {:<10} Resolución {:>3}".format(fname, RESOLUCION))
	
	data = fd.get_json_file(fname, RESOLUCION)
	
	cierre,apertura,high,low = fd.set_arrays_from_json_data(data)
	if cierre == None: 
		print ("Error al procesar ", fname)
		return 
	
	lecturas = len(cierre)	
	fecha = fb.get_fechas(data)
	
	
	
	file_path = os.path.join(DIRECTORIO_BASE, 'csv', RESOLUCION, fname + '.csv')	
	
	if os.path.exists(file_path):
		print ('\t\t Existe {}'.format(file_path))
		data = fd.cargar_valores(VALOR,RESOLUCION)
		datetime_json = datetime.strptime(fecha[-1], "%Y-%m-%d %H:%M")
		datetime_file = datetime.strptime(data['fecha'][-1], "%Y-%m-%d %H:%M")
		# nada que hacer, las fechas no son superiores
		if datetime_json <= datetime_file:
			cierre_json = cierre[-1]
			cierre_file = data['close'][-1]	
			if cierre_json == cierre_file:
				print ('\t\t Saliendo sin cambios, nada que anexar')
				# print ('\t\t', cierre_file, cierre_json)
				return
	
	# print (len(fecha), len(cierre),len(apertura),len(high),len(low))
	
	
	macd, macd_signal, macd_histograma = fb.get_macd(cierre,12,26,9)
	
	rsi14 = fb.calcular_rsi(14, cierre)
	rsi50 = fb.calcular_rsi(50, cierre)
	
	estocastico_sk_14, estocastico_sd_14 = fb.calcular_estocastico(cierre, high, low, 14, 3)
	estocastico_sk_50, estocastico_sd_50 = fb.calcular_estocastico(cierre, high, low, 14, 3)	
		
	# sma = [0]*201
	# ema = [0]*201
	
	#calcula emas de 5 a 200
	sma5 = fb.get_sma_periodo(5,cierre)
	ema5 = fb.get_ema_periodo(5,cierre)

	sma20 = fb.get_sma_periodo(20,cierre)
	ema20 = fb.get_ema_periodo(20,cierre)
	
	sma200 = fb.get_sma_periodo(200,cierre)
	ema200 = fb.get_ema_periodo(200,cierre)

	sma100 = fb.get_sma_periodo(100,cierre)
	ema100 = fb.get_ema_periodo(100,cierre)

	sma50 = fb.get_sma_periodo(50,cierre)
	ema50 = fb.get_ema_periodo(50,cierre)
	
	sma400 = fb.get_sma_periodo(400,cierre)
	ema400 = fb.get_ema_periodo(400,cierre)
	
	
	
	# print ('desde {} hasta {}'.format(fecha[0], fecha[-1]))
	
	directorio_destino =  os.path.join(DIRECTORIO_BASE, 'csv', RESOLUCION)	
	if not os.path.exists(directorio_destino):
		os.makedirs(directorio_destino)
		print ("creando directorio.... {}".format(directorio_destino))
	
	
	
	file_path = os.path.join(DIRECTORIO_BASE, 'csv', RESOLUCION, fname + '.csv')	
	if os.path.exists(file_path):		
		data = fd.cargar_valores(VALOR,RESOLUCION)
		
		datetime_json = datetime.strptime(fecha[-1], "%Y-%m-%d %H:%M")
		datetime_file = datetime.strptime(data['fecha'][-1], "%Y-%m-%d %H:%M")
			
		print ("\t\t anexando desde {}".format(data['fecha'][-1]))
		# print ('append fechas nuevas desde {} hasta {}'.format(data['fecha'][-1], fecha[-1] ))
	
		# aqui tenemos que modificar el ultimo valor en caso de que haya variacion
		# puedo cargar los valores a cargar en dataset y luego añadirlos al fichero csv
		# y luego recorrer el fichero y eliminar el penultimo valor
		
		with open( file_path, 'ab') as csvfile:
			spamwriter = csv.writer(csvfile, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL)
			# dataset = ['fecha','apertura','cierre','high','low','macd','macd_signal','macd_histograma','rsi14','rsi50','esk14','esd14','esk50', 'esd50','sma[5]','ema[5]','sma[20]','ema[20]','sma[50]','ema[50]','sma[100]','ema[100]','sma[200]','ema[200]','sma[400]','ema[400]']			
			# spamwriter.writerow(dataset)
				
			for x in range(0, len(fecha)):
				datetime_json = datetime.strptime(fecha[x], "%Y-%m-%d %H:%M")
				if datetime_json > datetime_file: # if datetime_json >= datetime_file: anade fila nueva	repitiendo		
					dataset = [fecha[x],apertura[x],cierre[x],high[x],low[x],macd[x],macd_signal[x],macd_histograma[x],rsi14[x],rsi50[x],estocastico_sk_14[x],estocastico_sd_14[x],estocastico_sk_50[x], estocastico_sd_50[x], sma5[x], ema5[x], sma20[x], ema20[x], sma50[x], ema50[x], sma100[x], ema100[x], sma200[x], ema200[x], sma400[x], ema400[x]]			
					spamwriter.writerow(dataset)
					# print ("\t\t Anadiendo {}".format(datetime_json))
				# else:
					# print ("\t\t Saliendo en {}".format(datetime_file))
		
	else:
		print ('\t\t nuevo {}'.format(file_path))
		with open( file_path, 'wb') as csvfile:
			spamwriter = csv.writer(csvfile, delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL)
			dataset = ['fecha','apertura','cierre','high','low','macd','macd_signal','macd_histograma','rsi14','rsi50','esk14','esd14','esk50', 'esd50','sma[5]','ema[5]','sma[20]','ema[20]','sma[50]','ema[50]','sma[100]','ema[100]','sma[200]','ema[200]','sma[400]','ema[400]']			
			spamwriter.writerow(dataset)
				
			for x in range(0,lecturas):
				dataset = [fecha[x],apertura[x],cierre[x],high[x],low[x],macd[x],macd_signal[x],macd_histograma[x],rsi14[x],rsi50[x],estocastico_sk_14[x],estocastico_sd_14[x],estocastico_sk_50[x], estocastico_sd_50[x], sma5[x], ema5[x], sma20[x], ema20[x], sma50[x], ema50[x], sma100[x], ema100[x], sma200[x], ema200[x], sma400[x], ema400[x]]			
				spamwriter.writerow(dataset)