1+ """ Scatter plots, Correlations, Beta and Alpha """
2+
3+ # Beta is a slope of the line. The steeper it is, the steeper the growth compared to market (SPY in this context).
4+ # e.g. If market goes 1% up, with Beta 2 the stock would go up 2%.
5+ # Beta shows how REACTIVE stock/asset is compared to the market.
6+ # Alpha is how much higher the line is above central cross. It means how much the stock outperforms the market.
7+ # Higher Alpha - better performance.
8+
9+ import pandas as pd
10+ import matplotlib .pyplot as plt
11+ import numpy as np
12+
13+ from daily_returns import get_data , plot_data
14+
15+ def compute_daily_returns (df ):
16+ daily_returns = df .copy ()
17+ daily_returns [1 :] = (df [1 :] / df [:- 1 ].values ) - 1
18+ daily_returns .ix [0 , :] = 0
19+ return daily_returns
20+
21+ def main ():
22+ # Read data
23+ dates = pd .date_range ("2009-01-01" , "2012-12-31" )
24+ symbols = ["SPY" , "XOM" , "GLD" ]
25+ df = get_data (symbols , dates )
26+ plot_data (df )
27+
28+ # Compute daily returns
29+ daily_returns = compute_daily_returns (df )
30+ plot_data (daily_returns , title = "Daily Returns" , ylabel = "Daily Returns" )
31+
32+ # Scatter plot SPY vs XOM
33+ daily_returns .plot (kind = "scatter" , x = "SPY" , y = "XOM" )
34+ beta_XOM , alpha_XOM = np .polyfit (daily_returns ["SPY" ], daily_returns ["XOM" ], 1 )
35+ plt .plot (daily_returns ["SPY" ], beta_XOM * daily_returns ["SPY" ] + alpha_XOM , "-" , color = "r" )
36+ print "XOM"
37+ print "Beta XOM: " , beta_XOM
38+ print "Alpha XOM: " , alpha_XOM
39+ print "\n "
40+ plt .show ()
41+
42+ # Scatter plot SPY vs GLD
43+ daily_returns .plot (kind = "scatter" , x = "SPY" , y = "GLD" )
44+ beta_GLD , alpha_GLD = np .polyfit (daily_returns ["SPY" ], daily_returns ["GLD" ], 1 )
45+ plt .plot (daily_returns ["SPY" ], beta_GLD * daily_returns ["SPY" ] + alpha_GLD , "-" , color = "y" )
46+ print "GLD"
47+ print "Beta GLD: " , beta_GLD
48+ print "Alpha GLD: " , alpha_GLD
49+ print "\n "
50+ plt .show ()
51+
52+ # Calculate correlation coefficient
53+ print daily_returns .corr (method = "pearson" )
54+
55+
56+
57+ if __name__ == "__main__" :
58+ main ()
0 commit comments