import datetime import pandas as pd import pandas.io.data from pandas import Series, DataFrame pd.__version__ import matplotlib.pyplot as plt import numpy as np %pylab inline sc='TSLA' stoxx = pd.io.data.get_data_yahoo(sc, start=datetime.datetime(2014, 1, 1)) stoxx.head(10) print('Date: %s' % stoxx.index[-1]) plt.figure(figsize=(16,4)) stoxx['Close'].plot(); plt.ylabel('\$') plt.title('Closing Price %s' % sc); plt.savefig('Closing-Price-TSLA.png',bbox_inches='tight', dpi=150) close_px = stoxx['Adj Close'] mavg10 = pd.ewma(close_px, 10) mavg30 = pd.ewma(close_px, 30) plt.figure(figsize=(16,4)) mavg10.plot(label='10days mavg'); mavg30.plot(label='30days mavg'); stoxx['Close'].plot(alpha=0.3); plt.ylabel('\$') plt.title('Exponentially Weighted Moving Averages %s' % (sc)); plt.legend(loc=2) plt.savefig('Closing-Price-TSLA-EWMA.png',bbox_inches='tight', dpi=150) # Get daily up or down delta = stoxx['Close'].diff() dUp, dDown = delta.copy( ), delta.copy( ) dUp[ dUp < 0 ] = 0 dDown[ dDown > 0 ] = 0 n=14 RolUp = pd.rolling_mean( dUp, n) RolDown = pd.rolling_mean( dDown, n).abs() RS = RolUp / RolDown RSI = 100. - 100./(1.+RS) plt.figure(figsize=(9,3)) RSI.plot(); plt.axhline(20, color='k', alpha=0.2) plt.annotate('oversold',xy=(0.5, 0.28), xycoords='figure fraction', fontsize=20, alpha=0.4, ha='center') plt.axhline(80, color='k', alpha=0.2) plt.annotate('overbought',xy=(0.5, 0.82), xycoords='figure fraction', fontsize=20, alpha=0.4,ha='center') plt.title('RSI %s (%i days)' % (sc, n)); plt.ylim([0,100]); plt.ylabel('%'); plt.savefig('RSI-TSLA.png',bbox_inches='tight', dpi=150) print('TSLA RSI (%s): %d%%' % (stoxx.index[-1], RSI.values[-1])) df = pd.io.data.get_data_yahoo(['AAPL', 'FXXP.EX', 'GOOG', 'FDAX.EX', 'TSLA'], start=datetime.datetime(2013, 1, 1))['Adj Close'] df.head() rets = df.pct_change() stoxx['rets'] = close_px.pct_change() plt.figure(figsize=(16,4)) stoxx.rets.plot(); plt.title('Returns %s' % sc); plt.ylabel('\$'); SO=stoxx['Close'][-1] # letzter Preis vol=np.std(stoxx['rets'])*np.sqrt(252) # Historical Volatility r=0.025 # Constant Short Rate K = SO*1.1 # 10% OTM Call Option T = 1.0 # Maturity 1 Year M=364 dt=T/M # Time Steps I = 100 # Simulation Paths S=np.zeros((M+1,I)) S[0,:]=SO for t in range(1, M+1): ran = np.random.standard_normal(I) S[t,:]=S[t-1,:] * np.exp((r-vol**2/2)*dt + vol*np.sqrt(dt)*ran) MC=pd.DataFrame(data=S, index=pd.date_range(start=stoxx.index[-1], periods=M+1)) MCmean = pd.DataFrame(data=S, index=pd.date_range(start=stoxx.index[-1], periods=M+1)).mean() ax=MC.plot(alpha=0.2, color='k'); stoxx['Close'].plot(ax=ax); plt.legend(['Monte Carlo Simulation'], loc='upper left'); plt.ylabel('Closing Price \$'); plt.title('Possible Future of TSLA (Tesla Motors Stock)') plt.savefig('Monte-Carlo-Simulation-TSLA.png',bbox_inches='tight', dpi=150) VO=np.exp(-r*T)*np.sum(np.max(S[-1]-K,0))/I print('Call Value %8.3f' % VO) fig=plt.figure(figsize=(12,12)); pd.scatter_matrix(rets, diagonal='kde', figsize=(10, 10)); corr = rets.corr() corr plt.imshow(corr, cmap='YlGn', interpolation='none') plt.colorbar() plt.xticks(range(len(corr)), corr.columns) plt.yticks(range(len(corr)), corr.columns); fig=plt.figure(figsize=(12,12)) plt.scatter(rets.mean(), rets.std(), s=50) plt.xlabel('Expected returns') plt.ylabel('Risk') for label, x, y in zip(rets.columns, rets.mean(), rets.std()): plt.annotate( label, xy = (x, y), xytext = (20, -20), textcoords = 'offset points', ha = 'right', va = 'bottom', bbox = dict(boxstyle = 'round,pad=0.5', fc = 'w', alpha = 0.5), arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))