BETA
- The Beta calculation is used to compare the volatility of a stock as compared to the market.
- SPY is usually used as the control_value for the market.
- A beta greater than 1 is a high volatility symbol.
- A beta less than 1 is less volatile than the market(SPY).
real = BETA(control_value, measured_value, timeperiod=5)
Plot
Working Example:from cloudquant import Strategy
import talib
class TAlibExample(Strategy):
@classmethod
def on_strategy_start(cls, md, service, account):
def match_bar_data(control_value, measured_value):
count = 0
del_list = []
for spy, symb in zip(control_value, measured_value):
# check nan
if symb != symb:
del_list.append(count)
count += 1
for number in del_list:
del control_value[number]
del measured_value[number]
return [control_value, measured_value]
# define a list of symbols to gather data for
cls.symbol_list = ['WMT', 'TGT', 'AAPL', 'MSFT', 'AMZN', 'FB', 'GOOGL', 'SBUX']
print 'Symbol\tBeta Calculation\n'
volatility_data = {}
bar_spy = md['SPY'].bar.daily(start=-252)
for x in md:
symbol = x.symbol
if symbol in cls.symbol_list:
bar = md[symbol].bar.daily(start=-252, include_empty=True)
bar_len = len(bar.high)
match_up = match_bar_data(bar_spy.close, bar.close)
spy = match_up[0]
cur_symbol_close = match_up[1]
if bar_len > 0:
timeperiod = 250
if bar_len < 250:
timeperiod = bar_len
calc_beta = talib.BETA(spy, cur_symbol_close, timeperiod=timeperiod)[-1]
volatility_data[symbol] = calc_beta
print 'Volatile Symbols:'
for symbol in volatility_data:
if volatility_data[symbol] > 1:
print '%s\t%s' % (symbol, volatility_data[symbol])
print '\nNon-Volatile Symbols:'
for symbol in volatility_data:
if volatility_data[symbol] < 1:
print '%s\t%s' % (symbol, volatility_data[symbol])
Console
Symbol Beta Calculation Volatile Symbols: AAPL 1.01361318547 FB 1.06762090307 AMZN 1.07973434029 MSFT 1.2127948511 Non-Volatile Symbols: GOOGL 0.952679576088 TGT 0.648991540915 WMT 0.487177826776 SBUX 0.909067976917