/
eggorder
/
demo_for_python_and_mr_integration
Обзор
Документация
Войти
/
eggorder
/
demo_for_python_and_mr_integration
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
integration_module.py
167 строк
7 KB
Egor
-
21 окт 2024, 13:36
21 окт 2024, 13:36
2b446cd
Код
Авторство
О чём код?
import pandas as pd import numpy as np import ctypes from ctypes import * from concurrent.futures import ProcessPoolExecutor import psutil import threading from psutil._common import bytes2human import time model_ptr = (c_longlong * 1)() # указатель на имитационную модель model_name = 'TEST_MODEL_MK' model_risk = ctypes.cdll.LoadLibrary('C:/MRService/Library/x64/MRService.dll') model_risk.MRLIB_CheckActivation.restype = ctypes.c_int model_risk.MRLIB_CheckActivation() model_risk.VoseNormalArray_Core.restype = c_bool model_risk.VoseNormalArray_Core.argtypes = [ ctypes.POINTER(c_double), c_int, c_double, c_double, ctypes.POINTER(c_double), ctypes.POINTER(c_int32), ctypes.POINTER(c_double), ctypes.POINTER(c_double), ctypes.POINTER(c_double), c_int32, ctypes.POINTER(c_wchar) ] def init_simulation_functions(): model_risk.MRLIB_CreateSimulationModel.restype = c_int model_risk.MRLIB_CreateSimulationModel.argtypes = [ctypes.POINTER(c_wchar), ctypes.POINTER(c_longlong)] model_risk.MRLIB_OpenSimulationModel.restype = c_int model_risk.MRLIB_OpenSimulationModel.argtypes = [ctypes.POINTER(c_wchar), ctypes.POINTER(c_longlong)] model_risk.MRLIB_OpenSimulationData.restype = c_int model_risk.MRLIB_OpenSimulationData.argtypes = [c_longlong] model_risk.MRLIB_AddModelVariable.restype = c_int model_risk.MRLIB_AddModelVariable.argtypes = [ c_longlong, c_int, ctypes.POINTER(c_wchar), ctypes.POINTER(c_wchar), ctypes.POINTER(c_wchar), c_int, ctypes.POINTER(c_wchar) ] model_risk.MRLIB_SetSimulationOptions.restype = c_int model_risk.MRLIB_SetSimulationOptions.argtypes = [c_longlong, c_int, c_int] model_risk.MRLIB_InitDefaultRandGeneratorBySID.restype = c_int model_risk.MRLIB_InitDefaultRandGeneratorBySID.argtypes = [c_int] model_risk.MRLIB_RunSimulationModel.restype = c_int model_risk.MRLIB_RunSimulationModel.argtypes = [c_longlong] model_risk.MRLIB_EndSimulationModel.restype = c_int model_risk.MRLIB_EndSimulationModel.argtypes = [c_longlong] model_risk.MRLIB_StartSimulation.restype = c_int model_risk.MRLIB_StartSimulation.argtypes = [c_longlong] model_risk.MRLIB_EndSimulation.restype = c_int model_risk.MRLIB_EndSimulation.argtypes = [c_longlong] model_risk.MRLIB_StartSample.restype = c_int model_risk.MRLIB_StartSample.argtypes = [c_longlong] model_risk.MRLIB_EndSample.restype = c_int model_risk.MRLIB_EndSample.argtypes = [c_longlong] model_risk.MRLIB_SaveVariableSample.restype = c_int model_risk.MRLIB_SaveVariableSample.argtypes = [c_longlong, c_int, c_double] model_risk.MRLIB_Model_SaveSimulationResultsToFile.restype = c_int model_risk.MRLIB_Model_SaveSimulationResultsToFile.argtypes = [c_longlong, ctypes.POINTER(c_wchar)] model_risk.MRLIB_GetModelData.restype = c_int model_risk.MRLIB_GetModelData.argtypes = [ c_longlong, c_int, c_int, ctypes.POINTER(c_double), c_int, c_int, c_int, ctypes.POINTER(c_int), ctypes.POINTER(c_int) ] model_risk.MRLIB_CloseSimulationModel.restype = c_int model_risk.MRLIB_CloseSimulationModel.argtypes = [c_longlong] def system_monitoring(): while True: print( f'|Current system-wide CPU utilization: {psutil.cpu_percent()}%\n' f'|System memory usage: {psutil.virtual_memory().percent}%\n' ) time.sleep(1) def one_trajectory(mu, sigma, S_0, n_outputs, index): error_buffer = (c_wchar * 50)() S = np.empty(n_outputs + 1) S[0] = S_0 W = (c_double * n_outputs)() model_risk.VoseNormalArray_Core( W, n_outputs, 0, 1, None, None, None, None, None, -1, error_buffer ) for t in range(1, n_outputs + 1): S[t] = S[t - 1] * np.exp((mu - sigma**2 / 2) + sigma * W[t - 1]) return index, S[1:] def modeling(historical_data, mu, sigma, S_0, n_outputs, n_samples): S = np.empty((n_outputs, n_samples)) start_time = time.perf_counter() with ProcessPoolExecutor() as executor: futures = [executor.submit(one_trajectory, mu, sigma, S_0, n_outputs, index) for index in range(n_samples)] for future in futures: index, trajectory = future.result() S[:, index] = trajectory init_simulation_functions() if model_risk.MRLIB_CreateSimulationModel(model_name, model_ptr) == 0: print('Не удалось создать модель!') sys.exit model_id = model_ptr[0] model_risk.MRLIB_OpenSimulationData(model_id) n_inputs = historical_data.size for i in range(n_inputs): model_risk.MRLIB_AddModelVariable(model_id, 1, f'Input {i}', '', '', 0, '') for i in range(n_outputs): model_risk.MRLIB_AddModelVariable(model_id, 0, f'Output {i}', '', '', 0, '') n_simulations = 1 model_risk.MRLIB_SetSimulationOptions(model_id, n_samples, n_simulations) if model_risk.MRLIB_RunSimulationModel(model_id) != 0: while model_risk.MRLIB_StartSimulation(model_id) != 0: sample = 0 while model_risk.MRLIB_StartSample(model_id) != 0: for i in range(n_inputs): model_risk.MRLIB_SaveVariableSample(model_id, i, historical_data[i]) for i in range(n_outputs): model_risk.MRLIB_SaveVariableSample(model_id, i + n_inputs, S[i, sample]) sample += 1 model_risk.MRLIB_EndSample(model_id) model_risk.MRLIB_EndSimulation(model_id) model_risk.MRLIB_EndSimulationModel(model_id) end_time = time.perf_counter() print(f'Время выполнения: {end_time - start_time:0.4f} секунд') result_path = 'C:\\MRService\\Python for ModelRisk Service Library\\OutputModel\\' \ + model_name + '.vmrs' model_risk.MRLIB_Model_SaveSimulationResultsToFile(model_id, result_path) if model_risk.MRLIB_CloseSimulationModel(model_id) == 0: print('Не удалось закрыть модель!') sys.exit if __name__ == "__main__": system_monitoring_thread = threading.Thread(target=system_monitoring) system_monitoring_thread.daemon = True system_monitoring_thread.start() historical_data = pd.read_excel( r'C:\Users\administrator\Downloads\мкпао-яндекс,-акция-об.-ru000a107t19.xlsx', header=1, usecols=['Закрытие'], nrows=30 ).iloc[:, 0].to_numpy() stock_profit = np.diff(historical_data) / historical_data[:-1] mu = np.mean(stock_profit) sigma = np.std(stock_profit) S_0 = historical_data[-1] n_outputs = 300 n_samples = 10000 modeling(historical_data, mu, sigma, S_0, n_outputs, n_samples)