# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# ## Stock Markets
#
# ### Internal Library
# Using [Alpha Vantage](https://www.alphavantage.co/). Free : 5 API requests per minute; 500 API requests per day. Use library function to use the cache/pickle as much as possible, to avoid exceeding free quote quota 
# - https://www.alphavantage.co/documentation/ 
# - https://en.wikipedia.org/wiki/List_of_S%26P_500_companies
# - https://github.com/twopirllc/pandas-ta/blob/master/examples/AIExample.ipynb

# +
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

plt.rcParams['figure.figsize'] = [20, 10]
# -

pd.read_csv('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=IBM&apikey=demo&datatype=csv',index_col=0)

# ### WGET
# Instead of hitting alphavantage everytime, we cache it in **wdata.AVGet()**

import wdata
abt = wdata.AVGet('ABT')
ibm = wdata.AVGet('IBM')

abt.iloc[::-1]['adjusted_close'].plot() # Time Series is reversed, [::-1] to reverse it

df1 = abt[['adjusted_close']].rename(columns={'adjusted_close': 'ABT'})
df1['IBM'] = ibm['adjusted_close']
df1['FB'] = wdata.AVGet('FB')['adjusted_close']
df1[::-1].plot()

# +
#import talib 
#abt['MA'] = talib.SMA(abt['adjusted_close'],100)
# -

abt[::-1][['adjusted_close','MA']].plot()

# ## Pandas-TA
# - https://github.com/twopirllc/pandas-ta
# - https://github.com/twopirllc/pandas-ta/blob/master/examples/AIExample.ipynb
# - pip install alphaVantage-api
# - pip install pandas-ta

# +
import pandas_ta as ta

asset = abt[:400][::-1].copy()

asset.ta.adjusted = "adjusted_close"
asset.ta.ema(length=8, append=True)
asset.ta.ema(length=21, append=True)
asset.ta.ema(length=50, append=True)

asset[asset.columns[5:]].tail()
# -

print(asset.ta.ema(length=2, append=False).head(5))
print(asset.close.head(5))

asset[["close", "EMA_8", "EMA_21", "EMA_50"]].plot()

# ### Trend Returns and Cumulative Trend Returns

long = ta.ema(asset.close, 8) > ta.ema(asset.close, 21)
trendy = asset.ta.trend_return(trend=long, cumulative=True, trade_offset=-1, append=True)
trendy.tail() # Third Column is the long trend; binary sequences

# ### Join
#
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html

# +
cltr = trendy.iloc[:,0]
tr = trendy.iloc[:,1]

trendy.iloc[:,:2].plot(figsize=(16, 3))
cltr.plot(figsize=(16, 3), kind="area", stacked=False, alpha=0.25, grid=True)

# +
capital = 10000

total_return = cltr.cumsum() * capital
positive_return = total_return[total_return > 0]
negative_return = total_return[total_return <= 0]
trdf = pd.DataFrame({"tr+": positive_return, "tr-": negative_return})
trdf.plot(figsize=(16, 5), kind="area", stacked=False, alpha=0.25, grid=True)

# +
long_trend = (trendy.iloc[:,-2] > 0).astype(int)
short_trend = (1 - long_trend).astype(int)

long_trend.plot(figsize=(16, 0.85), kind="area", stacked=True, alpha=0.25)
short_trend.plot(figsize=(16, 0.85), kind="area", stacked=True, alpha=0.25)

# +
entries = (trendy.iloc[:,-1] > 0).astype(int) * asset.close
entries[entries < 0.0001] = np.nan
entries.name = "Entry"

exits = (trendy.iloc[:,-1] < 0).astype(int) * asset.close
exits[exits < 0.0001] = np.nan
exits.name = "Exit"

total_trades = trendy.iloc[:,-1].abs().sum()
print(f"Total Trades: {total_trades}")

all_trades = trendy.iloc[:,-1].copy().fillna(0)
all_trades = all_trades[all_trades != 0]

trades = pd.DataFrame({"Signal": all_trades, entries.name: entries.dropna(), exits.name: exits.dropna()})
trades['PnL'] = (trades.Exit - trades.Entry.shift(1))  / trades.Entry.shift(1)
# -

(1 + trades.PnL).prod()

trades

asset.close - asset.close.shift(1)

# chart = asset["close"] #asset[["close", "SMA_10", "SMA_20", "SMA_50", "SMA_200"]]
# chart = asset[["close", "SMA_10", "SMA_20"]]
chart = asset[["close", "EMA_8", "EMA_21", "EMA_50"]]
chart.plot(figsize=(16, 10), grid=True)
entries.plot(figsize=(16, 10), marker="^", color='green', markersize=12, alpha=0.8)
exits.plot(figsize=(16, 10), marker="v", color='#FF0000', markersize=12, alpha=0.8, grid=True)



StarcoderdataJupyterScriptsDedupFiltered