0% found this document useful (0 votes)
16 views5 pages

Investing Py-Checkpoint

The Investing class is designed to analyze stocks using various financial metrics and strategies, including Ichimoku Cloud analysis and rolling averages. It allows users to filter stocks based on their budget, risk tolerance, and specific indices, while providing detailed statistics and trade particulars. Key functionalities include calculating eligible stocks, highlighting trends, and displaying expected changes and risks associated with potential investments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views5 pages

Investing Py-Checkpoint

The Investing class is designed to analyze stocks using various financial metrics and strategies, including Ichimoku Cloud analysis and rolling averages. It allows users to filter stocks based on their budget, risk tolerance, and specific indices, while providing detailed statistics and trade particulars. Key functionalities include calculating eligible stocks, highlighting trends, and displaying expected changes and risks associated with potential investments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

class Investing(AnalyseStocks):

def __init__(self,rolling_mean:int=44):
'''
args:
rolling_mean: Rolling Simple Mean to calulate
'''
super().__init__()
self.rm = rolling_mean
self._eligible = None
self.data = self.read_data()
self.indices = {'nifty_50': 'Nifty 50','nifty_100':'Nifty
100','nifty_200':'Nifty 200','nifty_500':'Nifty 500'}
self.all_ichi = None
self.picked = None
self._old_budget = -1
self.diff = -1

def _get_all_ichi(self,budget:float, index:str='nifty_500', refit = False):


'''
Get all Stocks who are almost perfect for Ichimoku execution
args:
budget: Your Budget
index: Which Index to Search
'''
if self.all_ichi and (not refit):
return self.all_ichi

all_ichi = {}
data = self.data[index] if index else self.all_stocks
for name in data:
df = self.Ichimoku_Cloud(self.open_downloaded_stock(name))
count = self._is_ichi(df,index)
if count and df.loc[0,'HIGH'] < budget:
all_ichi[name] = count

self.all_ichi = all_ichi
return self.all_ichi

def highlight_falling(self, s, column:str):


'''
Highlight The rows where average is falling
args:
s: Series
column: Column name(s)
'''
is_max = pd.Series(data=False, index=s.index)
is_max[column] = s.loc[column] == True
return ['' if is_max.any() else 'background-color: #f7a8a8' for v in
is_max]

def get_index(self,symbol:str):
'''
Get the Index of the symbol from nifty 50,100,200,500
args:
symbol: Name / ID od the company on NSE
'''
for index in self.indices.keys():
if symbol in self.data[index]:
return self.indices[index]
return 'Other'

def calculate(self, budget, High:str = 'HIGH', Close:str = 'CLOSE', delta:float


= 1, nifty:str = 'nifty_200', diff = 13, show_only:bool=True):
'''
Pick Stocks based on all available and which are within your budget
args:
budget: Total available budget. Stocks under this budget will be
considered only
High: Column name which show High
Close: Column Name which shows last closing price
delta: Value above the Last Highest Traded Price
nifty: nifty index to consider
show_only: If you want to see formatted part only
diff: Max Allowed Distance between Min(close,open,low,high) and High
'''
refit = True if (self._old_budget < budget or self.diff != diff) else False
self._old_budget = budget
self.diff = diff
ichi = self._get_all_ichi(budget ,refit = refit)

if (not self._eligible) or refit:


self._eligible = self.update_eligible(limit = diff)

keys = set(self._eligible.keys()).intersection(set(self.data[nifty])) if
nifty else list(self._eligible.keys())
if not len(keys):
warnings.warn('No matching Stocks Found. Increase Distance or Nifty
Index')
return None

values = []
one_can = []
two_can = []
three_can = []
atr = []
rsi = []

for key in keys:


try:
df = self.open_downloaded_stock(key)
except Exception as e:
print('Exception Opening: ',key)

if df.loc[0,High] + delta > budget:


del self._eligible[key]

else:
values.append(df.iloc[0,:])

one_can.append(CP.find_name(df.loc[0,'OPEN'],df.loc[0,'CLOSE'],df.loc[0,'LOW'],df.l
oc[0,'HIGH']))
two_can.append(CP.double_candle_pattern(df))
three_can.append(CP.triple_candle_pattern(df))
rsi.append(self.get_RSI(df))
atr.append(self.get_ATR(df))

columns = df.columns
df = pd.DataFrame(values,columns=columns,index = range(len(values)))
df = df.merge(pd.DataFrame({'SYMBOL':self._eligible.keys(),
'Diff':self._eligible.values()}),on='SYMBOL')

df['Rising'] = df['SYMBOL'].apply(lambda x: self.rising[x]) # Get Rising or


Falling
df['Ichi'] = df['SYMBOL'].apply(lambda x: ichi[x] if ichi.get(x) else 0)
df['RSI'] = rsi
df['ATR'] = atr

df['Triple Candle'] = three_can


df['Double Candle'] = two_can
df['Recent Candle'] = one_can

df['Index'] = df['SYMBOL'].apply(lambda x: self.get_index(x)) # Get Rising


or Falling

self.picked = df.sort_values('Diff',ascending = True)


if show_only:
return self.picked.style.apply(self.highlight_falling,
column=['Rising'], axis=1) # set style
else:
return self.picked

def show_full_stats(self, budget, risk, High = 'HIGH', Close = 'CLOSE',


delta:float=1, diff:float = 13, nifty:str = 'nifty_500',):
'''
Show Extra Stats
args:
budget: Total available budget. Stocks under this budget will be
considered only
risk: How much risk you want to take
High: Column name which show High
Close: Column Name which shows last closing price
delta: Value above the Last Highest Traded Price
nifty: nifty index to consider
diff: MAx Allowed Difference between Line and the Price
'''
self.picked = self.calculate(budget, High, Close, delta, nifty = nifty,
diff = diff, show_only = False)

expec_change = []
max_risk = []

if not isinstance(self.picked, pd.DataFrame):


return 'No match found. Increase Budget / Diff / Risk / Nifty Index '

pic = self.picked.copy()
for index in pic.index:
name = pic.loc[index,'SYMBOL']
result = self.get_particulars(name,budget,risk)
if result:
expec_change.append(result['Target %'])
max_risk.append(result['Max loss on this config'])
else:
expec_change.append(np.inf)
max_risk.append(np.inf)

pic['Expected Change %'] = expec_change


pic['Max Config Risk'] = max_risk
return pic

def get_particulars(self, name, budget:float, max_loss_capacity:float,


risk_to_reward_ratio:float=2, Low:str = 'LOW', High:str = 'HIGH', delta:float =
0.0033, plot_candle:bool = False):
'''
Display the particulars of a trade before buying
args:
name: name of the particular stock
loss_capacity: How much loss you can survive at the end of day PER
SHARE. Total capacity will be No of shares * per share loss capacity
risk_to_reward_ratio: How much profit you want to have. It is twice of
loss_capacity per share for 44 Moving average
budget : How much you have for investing purpose
Low: Column name which describes LOW of the previous trade
High = Column name which describes High of the previous trade
delta: A min amount above which you'll buy
plot_candle: Plot the candlestick for the stock
'''
df = self.open_downloaded_stock(name)
if risk_to_reward_ratio > 2:
warnings.warn(f"Don't be greedy with risk to reward ratio of
{risk_to_reward_ratio}. Stick to system")

if max_loss_capacity > 0.011 * budget:


warnings.warn(f"You are risking
{round(max_loss_capacity/budget,2)*100}% of your total PORTFOLIO. Going Like this,
you'll lose Rs {max_loss_capacity*15} in 15 Trades. Try keeping it less than 1.1% @
Rs {round(budget*0.011,2)}.")

buy_delta = df.loc[0,High] * delta


sell_delta = min(df.loc[:1,Low].values) * delta

risk = max_loss_capacity # per share

entry = df.loc[0,High] + buy_delta # Last Day MAX + Delta


stop_loss = min(df.loc[:1,Low].values) - sell_delta # Min of the last 2

max_loss = entry - stop_loss


stop_loss_perc = round((max_loss / entry) *100,2)
diff = entry - stop_loss
quantity = min(risk // diff , budget // entry)
profit = risk_to_reward_ratio * diff
profit_perc = round((profit/entry)*100,2)
target = round(entry + profit,2)

if plot_candle:
AnalyseStocks().plot_candlesticks(df)

if budget < entry:


warnings.warn(f"Budget for {name} should be a minimum of Rs. {entry}")
return None

if quantity < 1:
r = round(risk + (diff - risk), 2)
warnings.warn(f"Risk should be atleast {r} for you to afford {name}")
return None

return {'Buying Price':round(entry,2),'Stop-Loss %': stop_loss_perc,'Target


%':profit_perc,'Quantity':quantity,'Stop-Loss Price':stop_loss,'Trigger
Price':target,
'Risk Per Share':round(diff,2),'Profit Per
Share':round(profit,2),'Max loss on this config':round(quantity*diff,2),
'Max Gain on this config': round(quantity*profit,2),'Price To
Profit Ratio': round(entry / (diff*2 ),2), 'Index':self.get_index(name),}

In = Investing()

You might also like