コード例 #1
0
def new_calculator(dic, x):  # 計算新的標準差平均值
    avg = dic["avg"]
    std = dic["std"]
    count = dic["count"]
    n_count = count+1
    if n_count == 1:
        n_avg = round(x, 2)
        n_std = None
    elif n_count == 2:
        n_avg = round((avg*count+x)/(count+1), 2)
        n_std = round(statistics.sqrt((1/n_count)*(x-avg)**2), 2)
    else:
        n_avg = round((avg*count+x)/(count+1), 2)
        n_std = round(statistics.sqrt(((n_count-2)/(n_count-1))*(std**2)+(1/n_count)*(x-avg)**2), 2)
    return {"avg": n_avg, "std": n_std, "count": n_count}
コード例 #2
0
ファイル: step02_func_app.py プロジェクト: bis0908/Python
def var_std(data) :
    a = avg(data) # 산술평균 
    
    # list + for : (x - mu)**2
    diff = [(x-a)**2  for x in data]
    var = sum(diff) / (len(data) - 1) # 분산 
    std = sqrt(var) # 표준편차 
    
    return var, std
コード例 #3
0
def calculate_mhp_feature(timestamp,x,y,z):
    global mhp_buffer

    if len(mhp_buffer['timestamp']) == buffer_size:
        x_mhp = (x - statistics.mean(mhp_buffer['x']))**2
        y_mhp = (y - statistics.mean(mhp_buffer['y']))**2
        z_mhp = (z - statistics.mean(mhp_buffer['z']))**2
    else:
        x_mhp,y_mhp,z_mhp = 0,0,0

    return statistics.sqrt(x_mhp+y_mhp+z_mhp)
コード例 #4
0
def EVA(smb, n):
    """
    smb: pass an arrary or series here
    n  : n=12 for monthly data; n=250 for daily data
    """

    p = 0.99
    name = [
        "Annualized Mean", "t-statistics", "Annualized Volatility",
        "Sharpe Ratio", "Skewness", "Excess Kurtosis",
        "99%VaR(Cornish-Fisher)", "Annualized Downside Volatility",
        "Sortino Ratio", "Maximum Drawdown", "Max.Draw. Length", "CER"
    ]
    title = smb.name

    #annualized mean
    gm = (st.geometric_mean(smb + 1) - 1) * n
    mu = st.mean(smb)

    #annualized S.D.
    sd = st.stdev(smb)
    asd = st.sqrt(n) * st.stdev(smb)

    #annualized Sharpe
    sharpe = gm / asd

    #skewness and kurtosis
    skew = stats.skew(smb)
    kurt = stats.kurtosis(smb)

    #t-stats
    tvalue = stats.ttest_1samp(smb, 0)[0]

    #99% VaR-Cornish_Fisher
    inter = stats.norm.isf(p)
    zcf = inter + ((inter**2 - 1) * skew / 6) + (
        (inter**3 - 3 * inter) * kurt / 24) - ((2 * inter**3 - 5 * inter) *
                                               (skew**2) / 36)
    VaR = mu + sd * zcf * (-1)

    #downside volatility
    nret = smb.loc[smb < 0]
    dvola = st.stdev(nret) * st.sqrt(n)

    #sortino
    sortino = ((1 + mu)**n - 1) / dvola

    #maxmium drawdown
    uvi = (1 + smb).cumprod()
    dif = np.maximum.accumulate(uvi)  #return the largest value so far
    draw = uvi / dif - 1
    maxdraw = min(draw)
    ddend = np.argmin(draw)
    ddstart = np.argmax(uvi[:ddend])
    ddlength = ddend - ddstart

    #CER
    cer = ((1 + smb)**(1 - 5) - 1) / (-4)
    CER = st.mean(cer) * n

    #Export
    number = [
        gm, tvalue, asd, sharpe, skew, kurt, VaR, dvola, sortino, maxdraw,
        ddlength, CER
    ]
    output = pd.DataFrame({'Stats': name, title: number})
    print(output)
    return (output)
コード例 #5
0
                function_table=FUNCTION_TABLE,
                fit_function=fit_modulo_2,
                inputs_num=INPUTS_NUM,
                nodes_num=NODES_NUM,
                outputs_num=OUTPUTS_NUM,
                desired_fit=DESIRED_FIT,
                generations_num=GENERATIONS_NUM,
                mutation_prob=prob,
            )
            gens.append(solution.generation)
            muts.append(solution.total_mutations)
        # Store averages in respective lists
        avg_gens.append(mean(gens))
        avg_muts.append(mean(muts))
        # Standard error is stdev/sqrt(N)
        err_gens.append(stdev(gens) / sqrt(10))
        err_muts.append(stdev(muts) / sqrt(10))

    # Save data to a text file
    with open(FILEDIR + '/data.txt', mode='w') as f:
        for i, prob in enumerate(probabilities):
            f.write(f'{prob} {avg_gens[i]} {err_gens[i]} ' +
                    f'{avg_muts[i]} {err_muts[i]}\n')

    # Draw graphs with pyplot
    _, ax1 = plt.subplots(figsize=(12, 5))
    ax1.set_ylabel('Generations')
    ax1.set_xlabel('Probability')
    plt.errorbar(
        probabilities,
        avg_gens,
コード例 #6
0
# we can see here:-
# ['Counter', 'Decimal', 'Fraction', 'NormalDist', 'StatisticsError', '__all__', '__builtins__',
# '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_coerce',
# '_convert', '_exact_ratio', '_fail_neg', '_find_lteq', '_find_rteq', '_isfinite', '_normal_dist_inv_cdf',
# '_ss', '_sum', 'bisect_left', 'bisect_right', 'erf', 'exp', 'fabs', 'fmean', 'fsum', 'geometric_mean',
# 'groupby', 'harmonic_mean', 'hypot', 'itemgetter', 'log', 'math', 'mean', 'median', 'median_grouped',
# 'median_high', 'median_low', 'mode', 'multimode', 'numbers', 'pstdev', 'pvariance', 'quantiles', 'random',
# 'sqrt', 'stdev', 'tau', 'variance']

# lets discover some of the methods and attributes.
a = [20, 20, 20, 23, 34, 40, 45, 56, 67, 67, 67, 77]

# we can see we have exp, sqrt, log here. we also have the value of tau.
print(stat.exp(45))
# it raises e to the power of the input
print(stat.sqrt(90))
print(stat.log(100))
print(stat.tau)

# here we have different types of mean such as mean, harmonic_mean, geometric_men, fmean.
print(stat.mean(a))
print(stat.harmonic_mean(a))
# The harmonic mean, sometimes called the subcontrary mean, is the
# reciprocal of the arithmetic mean of the reciprocals of the data,
# and is often appropriate when averaging quantities which are rates
# or ratios, for example speeds. Example:
# Suppose an investor purchases an equal value of shares in each of
# three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
# What is the average P/E ratio for the investor's portfolio?
# >>> harmonic_mean([2.5, 3, 10])  # For an equal investment portfolio.
# 3.6
コード例 #7
0
ファイル: micromint.py プロジェクト: MaximilianSchon/EITN41
def calculateinterval(data):
    l = 3.66
    s = statistics.stdev(data)
    n = len(data)
    mean = statistics.mean(data)
    return [mean - l*s/statistics.sqrt(n), mean + l*s/statistics.sqrt(n)]
コード例 #8
0
# 변수 선택
x = data['cost']
x[:10]

# 1. 대표값
x.mean()

lst = x.to_list()  # pandas 객체 -> list 객체로
lst

st.mean(lst)

st.mean(x)
st.median(x)
st.median_low(x)
st.median_high(x)
st.mode(x)

x.value_counts()

# 2. 산포도: 분산, 표준편차
var = st.variance(x)
var

std = st.stdev(x)
std

std2 = st.sqrt(var)
std2
コード例 #9
0
def cohend(mean1, mean2, array1, array2):
    return abs(mean1 - mean2) / statistics.sqrt(
        (numpy.std(array1)**2 + numpy.std(array2)**2) / 2)
コード例 #10
0
import statistics
import math

agesData = [10, 13, 14, 12, 11, 10, 11, 10, 15]

print(statistics.mean(agesData))
print(statistics.mode(agesData))
print(statistics.median(agesData))
print(statistics.variance(agesData))
print(statistics.stdev(agesData))
print(statistics.sqrt(statistics.variance(agesData)))
コード例 #11
0
import math
import statistics
import cube
abc = dir(statistics)
#print(abc)
print(statistics.sqrt(4))
cube.cube(2)
コード例 #12
0
```

Let's try out the built-in **math** and **statistics** packages to do some calculating!

What is the mean of all the integers from 1 to 6?
"""

import statistics as stat
a_list = [1, 2, 3, 4, 5, 6]
stat.mean(a_list)
"""What is the standard deviation of the integers from 1 to 6?"""

stat.stdev(a_list)
"""What is the square root of 72?"""

stat.sqrt(72)
"""What is pi?"""

import math
pi = math.pi
print(pi)
"""What how many radians are in 360 degrees?"""

math.radians(360)
"""Can you find a package that might have functions for random numbers?  Use it to generate a couple random numbers!"""

import random

for i in range(3):
    random.randint(i + 1, 10)
"""Look for names of some more built-in packages online!  Try importing them here."""
コード例 #13
0
 def update_event(self, inp=-1):
     self.set_output_val(0, statistics.sqrt(self.input(0)))
コード例 #14
0
rerata = statistics.mean(data)
print(f"rerata = ({' + '.join(f'{x}' for x in data)}) / {len(data)}")
print(f'rerata = {rerata}')

print('\n===== Hitung varian =====')

# varian = [(bilangan - rerata) ** 2 for bilangan in data]

# mode verbose
list_varian = []
for bilangan in data:
    item = (bilangan - rerata)**2
    list_varian.append(item)

    print(f'({bilangan} - {rerata}) ^ 2 = {item}')

varian = sum(list_varian) / (len(data) - 1)

print('\ntotal =', ' + '.join(f'{item}' for item in list_varian))
print('total =', sum(list_varian))

print(f'\nvarian = {sum(list_varian)} / ({len(data) - 1})')
print(f'varian = {varian}')

simpangan_baku = statistics.sqrt(varian)
print('\n===== Simpangan Baku =====')
print('s = akar kuadrat dari varian')
print(f's = akar kuadrat({varian})')
print(f's = {simpangan_baku}')
# print(statistics.stdev(data))