import numpy as np

np.random.seed(1)

statistical_population = np.random.randint(2, size = 100000) 

random_sample = np.random.choice(statistical_population, size = 1000)

#истинное значение доли
statistical_population.mean()

"""
Explanation: Доверительные интервалы для доли
Генерация данных
End of explanation
"""


random_sample.mean()

"""
Explanation: Точечная оценка доли
End of explanation
"""


from statsmodels.stats.proportion import proportion_confint

"""
Explanation: Доверительный интервал для доли
End of explanation
"""


normal_interval = proportion_confint(sum(random_sample), len(random_sample), method = 'normal')

print 'normal_interval [%f, %f] with width %f' % (normal_interval[0],
                                                  normal_interval[1], 
                                                  normal_interval[1] - normal_interval[0])

"""
Explanation: Доверительный интервал на основе нормального распределения
$$\hat{p}\pm z_{1-\frac{\alpha}{2}} \sqrt{\frac{\hat{p}\left(1-\hat{p}\right)}{n}}$$
End of explanation
"""


wilson_interval = proportion_confint(sum(random_sample), len(random_sample), method = 'wilson')

print 'wilson_interval [%f, %f] with width %f' % (wilson_interval[0],
                                                  wilson_interval[1],
                                                  wilson_interval[1] - wilson_interval[0])

"""
Explanation: Доверительный интервал Уилсона
$$\frac1{ 1 + \frac{z^2}{n} } \left( \hat{p} + \frac{z^2}{2n} \pm z \sqrt{ \frac{ \hat{p}\left(1-\hat{p}\right)}{n} + \frac{
z^2}{4n^2} } \right), \;\; z \equiv z_{1-\frac{\alpha}{2}}$$
End of explanation
"""


from statsmodels.stats.proportion import samplesize_confint_proportion

n_samples = int(np.ceil(samplesize_confint_proportion(random_sample.mean(), 0.01)))
n_samples

np.random.seed(1)
random_sample = np.random.choice(statistical_population, size = n_samples)

normal_interval = proportion_confint(sum(random_sample), len(random_sample), method = 'normal')

print 'normal_interval [%f, %f] with width %f' % (normal_interval[0],
                                                  normal_interval[1],
                                                  normal_interval[1] - normal_interval[0])

"""
Explanation: Размер выборки для интервала заданной ширины
End of explanation
"""


