zoukankan      html  css  js  c++  java
  • 计算一个序列的移动平均线序列的模板,可实现均线的均线

    #pragma once
    //write by 陈墨仙 20150718
    //功能:计算序列的移动平均线,并返回序列
    template<class T>class funcMa
    {
    public:
        funcMa(){lastTick = 0;};
        ~funcMa(){};
        void clear()
        {
            t.clear();
            t.swap(vector<T>(t));
            lastTick = 0;
        }
        vector<T> Caculate(vector<T> p,int N,int direction)
        {
            
            int size = p.size() -1;

            if (size <= 0)
            {
                return t;
            }

            //vector<double> tSum;
            if (direction == 1)
            {
                for (;size > lastTick; size--)
                {
                    T sum = 0;
                    T ma = 0;
                    if(N > size)
                    {
                        N = size + 1;
                    }
                    for (int i = size; i > size - N; i--)
                    {
                        sum += p[i];
                    }
                    ma = sum/N;
                    //tSum.push_back(sum);
                    t.push_back(ma);
                }
                lastTick = size + 1;
            }
            else
            {
                for (int i = lastTick; i<=size; i++)
                {
                    T sum = 0;
                    T ma =0;
                    int temp = N;
                    if(temp > i)
                        temp = i + 1;

                    for(int j = i; j > i - temp; j--)
                    {
                        sum+=p[j];
                    }
                    ma = sum/temp;
                    t.push_back(ma);
                }

                lastTick = size + 1;
            }
            return t;
        }
    private:
        int lastTick;
        vector<T> t;

    };


    源码下载地址:http://download.csdn.net/detail/corivsky/8916855


    该代码的优点是。仅仅要不clear,就不会反复计算移动平均序列,当传入序列增大时。他会在原有基础上计算传入序列新增的数值。


    用法:
    static funcMa<double> ma60;
    static funcMa<double> ma2;
    static funcMa<double> ma22;
    
    static vector<double> C;//收盘价序列
    vector<double> ma60temp = ma60.Caculate(C,N*2,0);//收盘价的均线序列
    vector<double> ma2temp = ma2.Caculate(ma60temp,M1*2,0);//均线的均线
    vector<double> ma22temp =ma22.Caculate(ma2temp,M2*2,0);//均线的均线的均线

  • 相关阅读:
    [Chapter 3 Process]Practice 3.4 Describe what happens when a context switch occurs if the new context is already loaded into one of the register sets.
    [Chapter 3 Process]Practice 3.3 Discuss three major complications that concurrent processing adds to an operating system.
    爬取:中国大学排名
    基础统计学--复习
    pandas之数据结构
    numpy之初探排序和集合运算
    numpy之统计函数和布尔数组方法
    numpy之meshgrid和where
    numpy之通用函数ufunc
    numpy之转置(transpose)和轴对换
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/6834111.html
Copyright © 2011-2022 走看看