Есть библиотека для расчета индикаторов по техническому анализу. Ниже пример (не все идеально, как ориентир). Ссылка на библиотеку https://github.com/mrjbq7/ta-lib
#===================================================== # Импорт библиотек #===================================================== from iexfinance.stocks import get_historical_data import datetime import pandas as pd from pandas import DataFrame import talib as ta import matplotlib.pyplot as plt import seaborn as sns import psycopg2 import csv from sqlalchemy import create_engine import json import requests from sys import argv from scipy.signal import argrelextrema import numpy as np #===================================================== # ЗАГРУЗКА ДАННЫХ ИЗ API #===================================================== symbol = argv[1] interval = argv[2] urltext = 'https://api.binance.com/api/v1/klines?symbol='+symbol+'&interval='+interval result_req = requests.get(urltext) result_json = result_req.json() # Получаем наименования колонок array_data = [] for row in result_json: array_data.append({ 'open_time':row[0], 'date_time':datetime.datetime.fromtimestamp(row[0] / 1e3).strftime('%Y-%m-%d %H:%M:%S'), #utcfromtimestamp fromtimestamp #utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') 'dateformat':datetime.datetime.fromtimestamp(row[0] / 1e3).strftime('%Y.%m.%d %H:%M'), 'open':(row[1]), 'high':(row[2]), 'low':(row[3]), 'close':(row[4]), 'volume':(row[5]) }) # Формируем массив data data = pd.DataFrame(array_data) multipleCoeff = 1000 data['open']=pd.to_numeric(data['open']).mul(multipleCoeff) data['high']=pd.to_numeric(data['high']).mul(multipleCoeff) data['low']=pd.to_numeric(data['low']).mul(multipleCoeff) data['close']=pd.to_numeric(data['close']).mul(multipleCoeff) data['volume']=pd.to_numeric(data['volume']).mul(multipleCoeff) data.index = pd.to_datetime(data.date_time) #============================================== # ПОЛУЧАЕМ ПАРАМЕТРЫ ИЗ БАЗЫ ДАННЫХ #============================================== # 1. Подключаемся к базе данных PGSQL conn = psycopg2.connect(dbname='dbname', user='username', password='your_password', host='96.154.12.134') # 2. Получаем данные, кладем их в курсор cursor = conn.cursor() cursor.execute('select trim(parameter) parameter,value from ddt.calc_settings') # 3. Пишем paramData[] paramData = [] for paramRow in cursor: paramData.append(paramRow) # 4. Закрываем курсор cursor.close() conn.close() # 5. Устанавливаем переменные for row in enumerate(paramData): exec("%s=%s" % (row[1][0],row[1][1])) #===================================================== # Расчет #===================================================== #Фрактал n_min_max = 5 data['Fractal_UP'] = data.iloc[argrelextrema(data.low.values, np.less_equal, order=n_min_max)[0]]['low'] data['Fractal_Down'] = data.iloc[argrelextrema(data.high.values, np.greater_equal, order=n_min_max)[0]]['high'] # Обнуляем последний элемент массива по фракталу data['Fractal_UP'].iloc[-1] = np.nan data['Fractal_Down'].iloc[-1] = np.nan # Simple Moving Average data['SMA'] = ta.SMA(data.close, timeperiod = SMA_TimePeriod) # Exponential Moving Average data['EMA'] = ta.EMA(data.close, timeperiod = EMA_TimePeriod) # Bollinger Bands data['upper_band'], data['middle_band'], data['lower_band'] = ta.BBANDS(data.close, timeperiod = Bollinger_Bands_TimePeriod) # MACD data['macd'], data['macdsignal'], data['macdhist'] = ta.MACD(data.close, fastperiod=MACD_fastperiod, slowperiod=MACD_slowperiod, signalperiod=MACD_signalperiod) # RSI data['RSI'] = ta.RSI(data.close, timeperiod=RSI_TimePeriod) # OBV (On Balance Volume) data['OBV'] = ta.OBV(data.close, data.volume) #Alligator SMA data['SMA_green'] = ta.SMA(data.close, timeperiod = SMA_Green_TimePeriod) data['SMA_red'] = ta.SMA(data.close, timeperiod = SMA_Red_TimePeriod) data['SMA_blue'] = ta.SMA(data.close, timeperiod = SMA_Blue_TimePeriod) #Alligator EMA data['EMA_green'] = ta.EMA(data.close, timeperiod = EMA_Green_TimePeriod) data['EMA_red'] = ta.EMA(data.close, timeperiod = EMA_Red_TimePeriod) data['EMA_blue'] = ta.EMA(data.close, timeperiod = EMA_Blue_TimePeriod) #ADX data['ADX'] = ta.ADX(data.high, data.low, data.close, timeperiod=ADX_TimePeriod) data['MINUS_DI'] = ta.MINUS_DI(data.high, data.low, data.close, timeperiod=ADX_TimePeriod) data['PLUS_DI'] = ta.PLUS_DI(data.high, data.low, data.close, timeperiod=ADX_TimePeriod) data['TEMA'] = ta.TEMA(data.close, timeperiod=TEMA_TimePeriod) # Убираем масштабирование data['open'] = pd.to_numeric(data['open'])/multipleCoeff data['high'] = pd.to_numeric(data['high'])/multipleCoeff data['low'] = pd.to_numeric(data['low'])/multipleCoeff data['close'] = pd.to_numeric(data['close'])/multipleCoeff data['upper_band'] = pd.to_numeric(data['upper_band'])/multipleCoeff data['middle_band'] = pd.to_numeric(data['middle_band'])/multipleCoeff data['lower_band'] = pd.to_numeric(data['lower_band'])/multipleCoeff data['volume'] = pd.to_numeric(data['volume'])/multipleCoeff data['OBV'] = pd.to_numeric(data['OBV'])/multipleCoeff data['SMA'] = pd.to_numeric(data['SMA'])/multipleCoeff data['EMA'] = pd.to_numeric(data['EMA'])/multipleCoeff data['macd'] = pd.to_numeric(data['macd'])/multipleCoeff data['macdsignal'] = pd.to_numeric(data['macdsignal'])/multipleCoeff data['macdhist'] = pd.to_numeric(data['macdhist'])/multipleCoeff data['SMA_green'] = pd.to_numeric(data['SMA_green'].shift(periods=SMA_Green_Offset))/multipleCoeff data['SMA_red'] = pd.to_numeric(data['SMA_red'].shift(periods=SMA_Red_Offset))/multipleCoeff data['SMA_blue'] = pd.to_numeric(data['SMA_blue'].shift(periods=SMA_Blue_Offset))/multipleCoeff data['EMA_green'] = pd.to_numeric(data['EMA_green'].shift(periods=EMA_Green_Offset))/multipleCoeff data['EMA_red'] = pd.to_numeric(data['EMA_red'].shift(periods=EMA_Red_Offset))/multipleCoeff data['EMA_blue'] = pd.to_numeric(data['EMA_blue'].shift(periods=EMA_Blue_Offset))/multipleCoeff data['TEMA'] = pd.to_numeric(data['TEMA'])/multipleCoeff data['Fractal_UP'] = pd.to_numeric(data['Fractal_UP'])/multipleCoeff data['Fractal_Down'] = pd.to_numeric(data['Fractal_Down'])/multipleCoeff #===================================================== # JSON #===================================================== jsonstring = data.to_json(orient='records') print(jsonstring)
Вызвать скрипт можно из PHP, вот скрипт:
<?php //Получаем переменные из URL запроса if (isset($_GET['symbol']) and isset($_GET['interval'])) { $symbol = htmlspecialchars($_GET["symbol"]); $interval = htmlspecialchars($_GET["interval"]); } else { err(); } echo exec("python3 /home/admin/web/domain-name.ru/public_html/panel/98hlkjg987gtkbjbIUYG98iub/python_api/5_indicators.py ".$symbol." ".$interval); ?>
1 Comment