<jupyter_start><jupyter_text><jupyter_code>!pip install yfinance
import yfinance as yf
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.transforms as transform
import matplotlib.gridspec as gridspec
import pandas as pd
from pandas.tseries.offsets import MonthEnd
pd.options.mode.chained_assignment = None
pd.set_option('use_inf_as_na', True)
ticker = "SGRY"
start_date = dt.datetime(2010,12,31)
end_date = dt.datetime(2020,12,31)
class DataBase():
  def __init__(self, ticker, days):
    self.ticker = ticker
    data = yf.download(ticker, start = start_date, end =end_date )
    self.df = pd.DataFrame(data)
    pd.set_option("display.max_columns", None)
    self.df[self.df.index.dayofweek < 5]
    self.df= self.df[-days:]

  def quote(self):
    return self.df

db = DataBase(ticker, 1000)
df = db.quote()
print(df.tail())

df['MA_15'] = df['Adj Close'].rolling(window=15).mean()
df.dropna(inplace=True)

plt.rcParams.update({'font.size': 10})
fig, ax1 = plt.subplots(figsize = (15,6))
ax1.set_ylabel("Price in US$")
ax1.set_xlabel("Timestamp")
ax1.plot('Adj Close', data=df, label = "Adj Close Price")
ax1.plot('MA_15', data=df, label = "3 weeks MA"); plt.grid(True)
ax1.set_title('SGRY close price & 15 days rolling average')
plt.show()
df['price_change'] = df['Adj Close'].pct_change()
df = df.dropna()

# https://www.macroption.com/rsi/ 

df['up_move'] = df['price_change'].apply(lambda x: x if x > 0 else 0)
df['down_move'] = df['price_change'].apply(lambda x: abs(x) if x < 0 else 0)

df['avg_up'] = df['up_move'].ewm(span=19).mean()
df['avg_down'] = df['down_move'].ewm(span=19).mean()
df = df.dropna()

df['RS'] = df['avg_up'] / df['avg_down']
df = df.dropna()
df['RSI'] = df['RS'].apply(lambda x: 100 - (100/(x+1)))

df.loc[(df['Adj Close'] > df['MA_15']) & (df['RSI'] > 30), "BUY"] = 'YES'
df.loc[(df['Adj Close'] < df['MA_15']) | (df['RSI'] < 30), "BUY"] = 'NO'
df
pd.value_counts(df.BUY)
PnL = []

for i in range(len(df) - 12):
  if "YES" in df['BUY'].iloc[i]:
    for j in range(1,11):
      if df['RSI'].iloc[i+j] > 40:
        PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1])
        break
      if df['RSI'].iloc[i+j] < 40:
        PnL.append(df['Open'].iloc[i+12] - df['Open'].iloc[i+1])
        break

PnL
len([i for i in PnL if i > 0])
len(PnL)
# winning rate
print(len([i for i in PnL if i > 0]) / len(PnL))<jupyter_output>0.4949698189134809<jupyter_text>Function to calculate RSI<jupyter_code>tickers=["SGRY", "NTRA", "Z", "FATE", "DIS", "GM", 'BPMC', "PTC"]
start_date = dt.datetime(2015,12,31)
end_date = dt.datetime(2020,12,31)

def RSI_calculation(symbol):
  data = yf.download(tickers[0], start = start_date)
  data['MA_15'] = data['Adj Close'].rolling(window=15).mean()
  data['price_change'] = data['Adj Close'].pct_change()
  data['up_move'] = data['price_change'].apply(lambda x: x if x > 0 else 0)
  data['down_move'] = data['price_change'].apply(lambda x: abs(x) if x < 0 else 0)
  data['avg_up'] = data['up_move'].ewm(span=19).mean()
  data['avg_down'] = data['down_move'].ewm(span=19).mean()
  data = data.dropna()
  data['RS'] = data['avg_up'] / data['avg_down']
  data['RSI'] = data['RS'].apply(lambda x: 100 - (100/(x+1)))
  data.loc[(data['Adj Close'] > data['MA_15']) & (data['RSI'] > 30), "BUY"] = 'YES'
  data.loc[(data['Adj Close'] < data['MA_15']) | (data['RSI'] < 30), "BUY"] = 'NO'
  return (data)

def get_signals(data):
  buy_date = []
  sell_date = []

  for i in range(len(data) - 11):
    if "YES" in data['BUY'].iloc[i]:
      buy_date.append(data.iloc[i+1].name)
      for j in range(1,11):
        if data['RSI'].iloc[i+j] > 40:
          sell_date.append(data.iloc[i+j+1].name)
          break
        elif j == 10:
          sell_date.append(data.iloc[i+j+1].name)

  return (buy_date, sell_date)

dataframe = RSI_calculation(tickers[0])
buy, sell = get_signals(dataframe)

plt.figure(figsize = (15,6))
plt.scatter(dataframe.loc[buy].index, dataframe.loc[buy]['Adj Close'], 
            marker = '^', c = 'g')
plt.plot(dataframe['Adj Close'])
plt.grid(True); plt.show()
profits = (dataframe.loc[sell].Open.values - dataframe.loc[buy].Open.values) / dataframe.loc[sell].Open.values
len([i for i in profits if i > 0]) / len(profits)
len(profits)
matrix_signals = []
matrix_profit = []

for i in range(len(tickers)):
  dataframe = RSI_calculation(tickers[i])
  buy, sell = get_signals(dataframe)
  profits = (dataframe.loc[sell].Open.values - dataframe.loc[buy].Open.values) / dataframe.loc[sell].Open.values
  matrix_signals.append(buy)
  matrix_profit.append(profits)
final_profit = []

for i in matrix_profit:
  for e in i:
    final_profit.append(e)

final_profit
wins = [i for i in final_profit if i > 0]
len(wins) / len(final_profit)
plt.hist(final_profit, bins=100)
plt.show()<jupyter_output><empty_output><jupyter_text>Signals obtained in 2021<jupyter_code>for i in matrix_signals:
  for e in i:
    if e.year == 2021:
      print(e)<jupyter_output>2021-01-04 00:00:00
2021-01-06 00:00:00
2021-01-07 00:00:00
2021-01-08 00:00:00
2021-01-11 00:00:00
2021-01-12 00:00:00
2021-01-13 00:00:00
2021-01-14 00:00:00
2021-01-15 00:00:00
2021-01-19 00:00:00
2021-01-20 00:00:00
2021-01-21 00:00:00
2021-01-22 00:00:00
2021-01-25 00:00:00
2021-01-26 00:00:00
2021-01-29 00:00:00
2021-02-01 00:00:00
2021-02-02 00:00:00
2021-02-03 00:00:00
2021-02-04 00:00:00
2021-02-05 00:00:00
2021-02-08 00:00:00
2021-02-09 00:00:00
2021-02-10 00:00:00
2021-02-11 00:00:00
2021-02-12 00:00:00
2021-02-16 00:00:00
2021-02-17 00:00:00
2021-02-18 00:00:00
2021-02-22 00:00:00
2021-02-23 00:00:00
2021-02-24 00:00:00
2021-02-25 00:00:00
2021-02-26 00:00:00
2021-03-01 00:00:00
2021-03-02 00:00:00
2021-03-03 00:00:00
2021-03-04 00:00:00
2021-03-09 00:00:00
2021-03-10 00:00:00
2021-03-11 00:00:00
2021-03-12 00:00:00
2021-03-15 00:00:00
2021-03-16 00:00:00
2021-03-17 00:00:00
2021-03-18 00:00:00
2021-03-19 00:00:00
2021-03-23 00:00:00
2021-03-25 00:00:00
2021-03-26 00:00:00
[...]
{'fraction_non_alphanumeric': 0.19563025210084034, 'fraction_numerical': 0.146218487394958, 'mean_word_length': 4.390398550724638, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 23, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '351660', 'license': 'MIT', 'n_tokens_mistral': 3153, 'n_tokens_neox': 2607, 'n_words': 502, 'path': 'RSI_&_MA_strategy.ipynb', 'repo_name': 'saritmaitra/Momentum', 'size': '5950'}