 # stock moving average
import finnhub
import pandas as pd
from datetime import datetime
from datetime import timezone
import matplotlib.pyplot as plt
from numpy import *
import math

def MA(data, n):
    ma = data.rolling(window = n).mean()
    return ma
# bounds
def Bounds(data, sma, n, m):
    std = data.rolling(window = n).std()
    BOLU = sma + std * m
    BOLD = sma - std * m
    return BOLU, BOLD

finnhub_client = finnhub.Client(api_key = "bt3efpf48v6tfcs816eg")
start_time = int(datetime(2012, 1, 1, 0, 0).replace(tzinfo = timezone.utc).timestamp())
end_time = int(datetime(2021, 6, 10, 0, 0).replace(tzinfo = timezone.utc).timestamp())
# Stock candles
tsla = finnhub_client.stock_candles('TSLA', 'D', start_time, end_time)
tsla = pd.DataFrame(tsla)
tsla = tsla.rename(columns = {'t':'Date', 'o':'open', 'h':'high', 'l':'low','c':'close', 's':'status', 'v':'volumn'})

tsla['Date'] = pd.to_datetime(tsla['Date'], unit = 's')
tsla = tsla.set_index('Date')
tsla['TP'] = tsla.loc[:,['high', 'low', 'close']].mean(axis = 1) #typical price
tsla['MA'] = MA(tsla['TP'], 5) # 5-days moving average
tsla['BOLU'], tsla['BOLD'] = Bounds(tsla['TP'], tsla['MA'], 5, 2) # bounds
tsla['bb_w'] = (tsla['BOLU'] - tsla['BOLD'])/tsla['close'] # bounds width

tsla['long_entry'] = (tsla.low < tsla.BOLD) & (tsla.close >= tsla.BOLD) & (tsla.volumn > 10e6)
tsla_long_entry = tsla.loc[tsla.long_entry,['close']]

tsla['long_exit_upper'] = ((tsla.high > tsla.BOLU) & (tsla.close <= tsla.BOLU) & (tsla.volumn > 10e6))
tsla['long_exit_lower'] = ((tsla.low < tsla.BOLD) & (tsla.close <= tsla.BOLD) &(tsla.volumn > 10e6))
tsla['long_exit'] = (tsla.long_exit_upper) | (tsla.long_exit_lower)
tsla_long_exit_upper = tsla.loc[tsla.long_exit_upper,['close']]
tsla_long_exit_lower = tsla.loc[tsla.long_exit_lower,['close']]

tsla['trade'] = 0
tsla['buy'] = 0
tsla['sell'] = 0
ts = 0 # trading signal
for i in tsla.index:
    if ((tsla.loc[i, 'long_entry']) & (ts == 0)):
        ts = 1
# tsla.loc[i, 'cf'] = - tsla.loc[i, 'close']
        buy = tsla.loc[i, 'close']
        tsla.loc[i,'trade'] = -1
    if ((tsla.loc[i, 'long_exit']) & (ts == 1)):
        ts = 0
        tsla.loc[i, 'trade'] = 1
        tsla.loc[i, 'buy'] = buy
        tsla.loc[i, 'sell'] = tsla.loc[i, 'close']
        
tsla_long_entry = (tsla[tsla.trade != 0]).loc[tsla.long_entry,['close']]
tsla_long_exit = (tsla[tsla.trade != 0]).loc[tsla.long_exit,['close']]

fig, ax = plt.subplots()
tsla['close'].plot(label = 'CLOSE PRICES', color = 'skyblue', alpha=0.5, ax = ax)
tsla['BOLU'].plot(label = 'BOLU', linestyle = '--', linewidth = 1, color ='black', ax = ax)
tsla['MA'].plot(label = 'MOVING AVG', linestyle = '--', linewidth = 1.2, color= 'grey', ax = ax)
tsla['BOLD'].plot(label = 'BOLD', linestyle = '--', linewidth = 1, color ='black', ax = ax)
tsla_long_entry.reset_index().plot.scatter(x = 'Date', y = 'close', marker ='+', color = 'red',\
s = 200, ax = ax, label = 'Long␣ ,→Entry')
tsla_long_exit.reset_index().plot.scatter(x = 'Date', y = 'close', marker ='+', color = 'green',\
s = 200, ax = ax, label = 'Long Exit')
ax.vlines(tsla_long_entry.reset_index().Date, ymin = 0, ymax = 1000, color ='red',\
linestyle = '--', linewidth = 1, label = 'Long Entry')
ax.vlines(tsla_long_exit.reset_index().Date, ymin = 0, ymax = 1000, color ='green',\
linestyle = '--', linewidth = 1, label = 'Long Exit')
    
tsla['rtn'] = (tsla['sell'] - tsla['buy']) / tsla['buy']
tsla = tsla.fillna(0)
tsla['cum_rtn'] = (1 + tsla.rtn).cumprod()
tsla['cum_rtn']

spy = finnhub_client.stock_candles('SPY', 'D', start_time, end_time)
spy = pd.DataFrame(spy)
spy = spy.rename(columns = {'t':'Date', 'o':'open', 'h':'high', 'l':'low', 'c': 'close', 's':'status', 'v':'volumn'})
spy['Date'] = pd.to_datetime(spy['Date'], unit = 's')
spy = spy.set_index('Date')
spy['close_lagged'] = spy['close'].shift(1)
# spy['rtn'] = (spy['close'] - spy['close_lagged']) / spy['close_lagged']
spy['pct_rtn'] = spy['close'].pct_change()
spy['cum_rtn'] = (1 + spy.pct_rtn).cumprod()
spy = spy.dropna()
spy.head()
        
comb = spy.join(tsla, lsuffix = '_market', rsuffix = '_bollinger')
comb = comb.dropna()
        

fig, ax = plt.subplots()
comb['cum_rtn_market'].plot(label = 'Market Return', color = 'skyblue', ax = ax)
comb['cum_rtn_bollinger'].plot(label = 'Bollinger Return', color ='mediumvioletred', ax = ax)
# ax.vlines(tsla_long_entry.reset_index().Date, ymin = -0.25, ymax = 1.75,␣ ,→color = 'red',\
# linestyle = '--', linewidth = 1, label = 'Long Entry')
# ax.vlines(tsla_long_exit.reset_index().Date, ymin = -0.25, ymax = 1.75, color␣ ,→= 'green',\
# linestyle = '--', linewidth = 1, label = 'Long Exit Upper')
plt.legend(loc = 'upper left')
plt.title('Return Comparison')
plt.show()
        
        
        