marketTrade/Core/Ind_Stochastic.py
2022-03-05 23:57:24 +03:00

148 lines
3.6 KiB
Python

import pandas as pd
import datetime
import numpy as np
import plotly as pl
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import math
import scipy
import random
import statistics
import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import mplfinance as mpf
import plotly
#import plotly.plotly as py
import plotly.graph_objs as go
# these two lines allow your code to show up in a notebook
from plotly.offline import init_notebook_mode, iplot
from plotly.subplots import make_subplots
init_notebook_mode()
import CoreTraidMath
import CoreDraw
class Stochastic:
def __init__(self, base_df, options={
'dataType':'ohcl',
'window':14,
'windowSMA':5
}, needFig=False,showOnlyIndex=True,drawFig=False
):
self.base_df=base_df.reset_index(drop=True)
self.options=options
self.ans=self.getAns()
if needFig:
self.fig=self.pltShow(showOnlyIndex,drawFig)
def getKn(self):
ans={}
y=np.asarray([])
x=np.asarray([])
for i in range(self.options['window'],self.base_df.shape[0]):
minValue=min(self.base_df['low'][i-self.options['window']:i])
maxValue=max(self.base_df['high'][i-self.options['window']:i])
y=np.append(y,(self.base_df['close'][i-1]-minValue)/(maxValue-minValue))
x=np.append(x,self.base_df['date'][i-1])
#print(i,minValue,maxValue,self.base_df[self.options['colName']['close']][i],y[-1])
ans['y'],ans['x']=y,x
return ans
def getSMA(self,col):
ans=None
ser = pd.Series(col, copy=False)
op={'dataType':'series',
'action':'findMean',
'actionOptions':{'MeanType':'SMA','window':self.options['windowSMA']}
}
ans=np.asarray(CoreTraidMath.CoreMath(ser,op).ans)
return ans
#return np.convolve(col, np.ones(self.options['windowSMA']), 'valid') /self.options['windowSMA']
def getDn(self,col):
ans={}
y=np.asarray([])
x=np.asarray([])
for i in range(self.options['windowSMA'],len(col['y'])):
y=np.append(y, self.getSMA(col['y'][i-self.options['windowSMA']:i]))
x=np.append(x,col['x'][i])
ans['y'],ans['x']=y,x
return ans
def getAns(self):
ans={}
ans['Kn']=self.getKn()
ans['Dn']=self.getDn(ans['Kn'])
#print(ans)
return(ans)
def pltShow(self,showOnlyIndex,drawFig):
ans=None
req=[]
row=1
if not showOnlyIndex:
row=2
req.append({
'vtype':'OCHL',
'df':self.base_df,
'row':1,
'col':1,
'name':'OHCL'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['Kn']['y'],'date':self.ans['Kn']['x']}) ,
'row':row,
'col':1,
'name':'Kn'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['Dn']['y'],'date':self.ans['Dn']['x']}) ,
'row':row,
'col':1,
'name':'Dn'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans