Python 下載 tushare 數據,而後調用 C++ DLL 計算 wMA 存入本地 csv 文件再 python 讀取

CMakeLists.txtpython

project(wMA)
add_library(wMA SHARED wMA.cpp)

wMA.hmysql

#pragma once

#ifndef WMA_WMA_H
#define WMA_WMA_H
#endif

#ifdef BUILD_WMA_DLL
#define IO_WMA_DLL __declspec(export)
#else
#define IO_WMA_DLL __declspec(import)
#endif

extern "C"
{
IO_WMA_DLL int wMA(double array[], int arrayLen, int n);
}

wMA.cppios

#define BUILD_WMA_DLL

#include "wMA.h"
#include <iostream>
#include <fstream>

using namespace std;

IO_WMA_DLL int wMA(double array[], int arrayLen, int n)
{
    cout << "歡迎光臨..." << endl;
    cout << "開始計算..." << endl;
    int m = n;
    double wMA[arrayLen];
    if(arrayLen >= n && n >= 0)
    {
        switch(n)
        {
            case 0:
            {
                cout << "長度爲零..." << endl;
                for(int i = 0; i < m; i++)
                {
                    wMA[i] = 0;
                }
                break;
            }
            default:
            {
                for(int i = 0; i < m - 1; i++)
                {
                    wMA[i] = 0;
                }
                while(arrayLen >= m)
                {
                    double temp = 0;
                    for(int i = m - n, j = 0; i < m; i++, j++)
                    {
                        temp += array[i] * j;
                    }
                    wMA[m - 1] = temp / n;
                    m++;
                }
                break;
            }
        }
    }
    else
    {
        cout << "長度錯誤..." << endl;
    }
    cout << "存入文件..." << endl;
    ofstream fWMA("c:\\wMA.csv");
    if(!fWMA)
    {
        cout << "打開錯誤..." << endl;
        return -1;
    }
    else
    {
        fWMA << "Index" << "," << "index of sh" << "," << "wMA" << "," << endl;
        for(int i = 0; i < arrayLen; ++i)
        {
            fWMA << i << "," << array[i] << "," << wMA[i] << "," << endl;
        }
        cout << "完成寫入..." << endl;
        fWMA.close();
        return 1;
    }
}

wMA.pysql

import tushare
from ctypes import *
# 數據預處理
dataFrame = tushare.get_hist_data('sh')
open = dataFrame['open'].values
openLen = len(open)
# python 的 list 格式轉爲 c 的 array 格式
array = (c_double * openLen)(*open)
arrayLen = openLen
# 調用 DLL 函數 wMA 算出 wMA 值存入文件
hDLL = CDLL('C:\\Users\\Perelman\\.CLion2016.1\\system\\cmake\\generated\\wMA-4d5bfe42\\4d5bfe42\\Debug\\libwMA.dll')
print(hDLL.wMA(array, arrayLen, 5))

 

1 2

讀取 csv,調整後存數據庫,python socket 和 mysql 部分見其餘隨筆,數據庫

import pandas
dataFrame = pandas.DataFrame(pandas.read_csv("c:\\wMA.csv"))
print(dataFrame)
dataFrame = dataFrame.drop(['Unnamed: 3'], axis=1)
print(dataFrame)

1

相關文章
相關標籤/搜索