예제 #1
0
 def __init__(self, gals, galRedshiftErrors, zR, eventSelector, **kwargs):
     Beta.__init__(self, **kwargs)
     self.eventSelector = eventSelector
     self.gals = gals
     self.zR = zR
     self._galRedshiftErrors = galRedshiftErrors
     self._nside = 1024
예제 #2
0
    def __init__(self, strategy, index_code=None):
        """
        :param strategy: 策略
        :param index_code: index基准利率代码应该同tushare保持一致
        sh 上证指数 sz 深圳成指 hs300 沪深300指数 sz50 上证50指数 zxb 中小板指数 cyb 创业板指数
        :return:
        """
        self.__baseRet_code = index_code
        self.__baseRet_data = None
        self.__currBaseRet = []
        self.__last_baseRet = 0.0
        self.__baseRet = dataseries.SequenceDataSeries()
        self.__betaRet = dataseries.SequenceDataSeries()
        self.__alphaRet = dataseries.SequenceDataSeries()
        self.__sharpeRet = dataseries.SequenceDataSeries()
        self.__LongestDrawDown = dataseries.SequenceDataSeries()
        self.__MaxDrawDown = dataseries.SequenceDataSeries()
        self.__ret_analyzer = returns.Returns()
        self.__sharpe_ratio = sharpe.SharpeRatio(False)
        self.__draw_down = drawdown.DrawDown()
        self.__beta = Beta()

        strategy.attachAnalyzer(self.__ret_analyzer)
        strategy.attachAnalyzer(self.__sharpe_ratio)
        strategy.attachAnalyzer(self.__draw_down)
        strategy.attachAnalyzer(self.__beta)
        strategy.attachAnalyzer(self)
예제 #3
0
 def __init__(self, zR, lamb=1, **kwargs):
     Beta.__init__(self, **kwargs)
     self.zR = zR
     self.lamb = lamb
예제 #4
0
from f_dist import F_dist
from gamma import Gamma
from inv_gamma import Inverse_gamma
from student_t import Student_t
from uniform import Uniform
from numpy import array

x = array([1.2, 1.5, 2.1, 5.4])
x2 = array([.1, .3, .4, .7])

mu, sigma, alpha, beta, k, gamma, d1, d2, kk, theta = [1.2, 2.3, .4, .5, 4,
                                                       3, 4, 6, 1.6, .7]

lnorm = Lognorm(mu, sigma)
norm = Normal(mu, sigma)
beta = Beta(alpha, beta)
chi = Chi(k)
chi2 = Chi_square(k)
exp = Exponential(gamma)
f = F_dist(d1, d2)
gamma = Gamma(kk, theta)
invgamma = Inverse_gamma(mu, sigma)
t = Student_t(d2)
uniform = Uniform(alpha, d2)

print 'lnorm.cdf(x): ', lnorm.cdf(x)
print 'norm.cdf(x): ', norm.cdf(x)
print 'beta.cdf(x2): ', beta.cdf(x2)
print 'chi.cdf(x): ', chi.cdf(x)
print 'chi2.cdf(x): ', chi2.cdf(x)
print 'exp.cdf(x): ', exp.cdf(x)
예제 #5
0
class Analyzer(object):
    """
    此类是对pyalgotrade中原有的stratanalyzer进行封装
    将所有的分析结果都在此类中处理,并对结果进行保存
    """
    def __init__(self, strategy, index_code=None):
        """
        :param strategy: 策略
        :param index_code: index基准利率代码应该同tushare保持一致
        sh 上证指数 sz 深圳成指 hs300 沪深300指数 sz50 上证50指数 zxb 中小板指数 cyb 创业板指数
        :return:
        """
        self.__baseRet_code = index_code
        self.__baseRet_data = None
        self.__currBaseRet = []
        self.__last_baseRet = 0.0
        self.__baseRet = dataseries.SequenceDataSeries()
        self.__betaRet = dataseries.SequenceDataSeries()
        self.__alphaRet = dataseries.SequenceDataSeries()
        self.__sharpeRet = dataseries.SequenceDataSeries()
        self.__LongestDrawDown = dataseries.SequenceDataSeries()
        self.__MaxDrawDown = dataseries.SequenceDataSeries()
        self.__ret_analyzer = returns.Returns()
        self.__sharpe_ratio = sharpe.SharpeRatio(False)
        self.__draw_down = drawdown.DrawDown()
        self.__beta = Beta()

        strategy.attachAnalyzer(self.__ret_analyzer)
        strategy.attachAnalyzer(self.__sharpe_ratio)
        strategy.attachAnalyzer(self.__draw_down)
        strategy.attachAnalyzer(self.__beta)
        strategy.attachAnalyzer(self)

    def get_analyzerReturn(self):
        analyzerReturn = DataFrame()
        if self.__baseRet_code is not None:
            analyzerReturn["baseRet"] = np.array(self.__baseRet)
        analyzerReturn["date"] = np.array(self.__ret_analyzer.getReturns().getDateTimes())
        analyzerReturn['current_returns'] = np.array(self.__ret_analyzer.getReturns()) * 100
        analyzerReturn['total_returns'] = np.array(self.__ret_analyzer.getCumulativeReturns()) * 100
        analyzerReturn['MaxDrawDown'] = np.array(self.__MaxDrawDown) * 100
        analyzerReturn['LongestDrawDownDuration'] = np.array(self.__LongestDrawDown)
        analyzerReturn['sharpe'] = np.array(self.__sharpeRet)
        analyzerReturn['beta'] = np.array(self.__betaRet)
        analyzerReturn['alpha'] = np.array(self.__alphaRet)
        analyzerReturn = analyzerReturn.set_index('date')
        return analyzerReturn

    def __get_baseRet_data(self, bars):
        if self.__baseRet_code is not None:
            startdate = str((bars.getDateTime()-datetime.timedelta(days=1)).strftime('%Y-%m-%d'))
            import tushare as ts
            data = ts.get_hist_data(self.__baseRet_code, start=startdate)
            self.__baseRet_data = pd.DataFrame(data)

    def __append_baseRet(self, bars):
        date = str(bars.getDateTime().strftime('%Y-%m-%d'))
        self.__last_baseRet = self.__last_baseRet + self.__baseRet_data['p_change'][date]
        # 当日涨跌幅
        self.__currBaseRet.append(self.__baseRet_data['p_change'][date])
        # 累计涨跌幅
        self.__baseRet.appendWithDateTime(date, self.__last_baseRet)

    def beforeOnBars(self, strat, bars):

        if self.__baseRet_code is not None and self.__baseRet_data is None:
            self.__get_baseRet_data(bars)
            self.__append_baseRet(bars)
        else:
            self.__append_baseRet(bars)

        self.__LongestDrawDown.appendWithDateTime(str(bars.getDateTime().strftime('%Y-%m-%d')),
                                                  self.__draw_down.getLongestDrawDownDuration().days)
        self.__MaxDrawDown.appendWithDateTime(str(bars.getDateTime().strftime('%Y-%m-%d')),
                                              self.__draw_down.getMaxDrawDown())
        self.__sharpeRet.appendWithDateTime(str(bars.getDateTime().strftime('%Y-%m-%d')),
                                            self.__sharpe_ratio.getSharpeRatio(0.04))
        self.__betaRet.appendWithDateTime(str(bars.getDateTime().strftime('%Y-%m-%d')),
                                          self.__beta.getBeta(np.array(self.__currBaseRet)))
        self.__alphaRet.appendWithDateTime(str(bars.getDateTime().strftime('%Y-%m-%d')),
                                           self.__beta.getAlpha(np.array(self.__baseRet)))

    def beforeAttach(self, strat):
        pass

    def attached(self, strat):
        pass
예제 #6
0
from beta import Beta
from joint import Joint

value1 = Beta(0.5, 0.5)
value2 = Beta(2.0, 5.0)

joint_sum = Joint(value1, value2, "Sum")
joint_quotient = Joint(value1, value2, "Quotient")
joint_product = Joint(value1, value2, "Product")
joint_quadro_sum = Joint(value1, value2, "QuadroSum")
joint_min = Joint(value1, value2, "Min")
joint_max = Joint(value1, value2, "Max")

print("BETA VALUE 1", value1.mean, value1.variance, value1.pdf(0.5), value1.cdf(0.5))
print("BETA VALUE 2", value2.mean, value2.variance, value2.pdf(0.5), value2.cdf(0.5))

print("JOINT SUM", joint_sum.mean, joint_sum.variance, joint_sum.pdf(0.5), joint_sum.cdf(0.5))
print("JOINT QUOTIENT", joint_quotient.mean, joint_quotient.variance, joint_quotient.pdf(0.5), joint_quotient.cdf(0.5))
print("JOINT PRODUCT", joint_product.mean, joint_product.variance, joint_product.pdf(0.5), joint_product.cdf(0.5))
print(
    "JOINT QUADRO SUM",
    joint_quadro_sum.mean,
    joint_quadro_sum.variance,
    joint_quadro_sum.pdf(0.5),
    joint_quadro_sum.cdf(0.5),
)
print("JOINT MIN", joint_min.mean, joint_min.variance, joint_min.pdf(0.5), joint_min.cdf(0.5))
print("JOINT MAX", joint_max.mean, joint_max.variance, joint_max.pdf(0.5), joint_max.cdf(0.5))

joint_sum.show("pdf")
# joint_quotient.show("pdf")
예제 #7
0
from gamma import Gamma
from inv_gamma import Inverse_gamma
from student_t import Student_t
from uniform import Uniform
from numpy import array

x = array([1.2, 1.5, 2.1, 5.4])
x2 = array([.1, .3, .4, .7])

mu, sigma, alpha, beta, k, gamma, d1, d2, kk, theta = [
    1.2, 2.3, .4, .5, 4, 3, 4, 6, 1.6, .7
]

lnorm = Lognorm(mu, sigma)
norm = Normal(mu, sigma)
beta = Beta(alpha, beta)
chi = Chi(k)
chi2 = Chi_square(k)
exp = Exponential(gamma)
f = F_dist(d1, d2)
gamma = Gamma(kk, theta)
invgamma = Inverse_gamma(mu, sigma)
t = Student_t(d2)
uniform = Uniform(alpha, d2)

print 'lnorm.cdf(x): ', lnorm.cdf(x)
print 'norm.cdf(x): ', norm.cdf(x)
print 'beta.cdf(x2): ', beta.cdf(x2)
print 'chi.cdf(x): ', chi.cdf(x)
print 'chi2.cdf(x): ', chi2.cdf(x)
print 'exp.cdf(x): ', exp.cdf(x)
예제 #8
0
db.echo = False  # Try changing this to True and see what happens

# metadata = MetaData(db)

SessionClass = sessionmaker(bind=db)
session = SessionClass()

review_count = 100
reviews = session.query(TestReview).limit(review_count).all()

successes = {}
successes['simple_bayes'] = 0
successes['probability'] = 0
successes['naive_bayes'] = 0

for i,review in enumerate(reviews):
	sentiment = Beta(session, review.comment)
	given = review.known_score

	print "-----Iteration " + str(i+1) + "---------- words-" + str(len(sentiment.words))
	print given
	for test in ['simple_bayes', 'probability', 'naive_bayes']:
		calculated_score = sentiment.get_score(test)
		if given in [4,5] and calculated_score > 0:
			successes[test] = successes[test] + 1
		elif given in [1,2] and calculated_score < 0:
			successes[test] = successes[test] + 1
		print test, "-", calculated_score, "-", float(successes[test])/(i+1)*100

예제 #9
0
 def __init__(self, dMax, zR=10, **kwargs):
     Beta.__init__(self, **kwargs)
     self.dMax = dMax