changing structure

This commit is contained in:
2022-05-10 14:27:43 +03:00
parent 6dfe72a3d9
commit c2ddfc0536
23 changed files with 144 additions and 154 deletions

View File

@@ -0,0 +1,199 @@
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 plotly.express as px
class agrigateFig():
def __init__(self,data=[],needDraw=False ,subplot_titles=None):
self.data=data
self.ans=self.getAgrPlt()
if needDraw:
self.subplot_titles=subplot_titles
self.fig=coreDraw(self.ans,True,self.subplot_titles)
def getAgrPlt(self):
count=0
ans=[]
for i in self.data:
count=count+1
if type(i)==list:
for g in i:
for j in g.figDict:
ans.append(j)
ans[-1]['row']=count
else:
for j in i.figDict:
ans.append(j)
ans[-1]['row']=count
return ans
class corePlt():
def __init__(self, params={
'vtype':'',
'df':pd.DataFrame(),
'row':1,
'col':1,
'name':''
}):
self.vtype=params['vtype']
self.df=params['df']
self.row=params['row']
self.col=params['col']
self.name=params['name']
if 'colorType' in params.keys():
self.colorType=params['colorType']
class coreDraw():
def __init__(self, data=[],needShow=False):
self.data=self.getPlts(data)
self.needShow=needShow
self.ans=self.getAns()
def getBarColorList(self,l,colorType):
if colorType=='diffAbs':
ans=['green']
for i in range(1,len(l)):
if abs(l[i])>abs(l[i-1]):
ans.append('green')
else:
ans.append('red')
elif colorType=='diff':
ans=['green']
for i in range(1,len(l)):
if (l[i])>(l[i-1]):
ans.append('green')
else:
ans.append('red')
elif colorType=='normal':
ans=[]
for i in range(len(l)):
ans.append('gray')
return ans
def getPlts(self, data):
ans=None
if type(data)==list:
ans=[]
for i in data:
ans.append(corePlt(i))
else:
ans=[corePlt(data)]
return ans
def getAns(self):
'''
data list
vtype
df
row=1
col=1
name
'''
ans=None
maxRow=1
maxCol=1
for i in self.data:
if i.row > maxRow:
maxRow =i.row
if i.col > maxCol:
maxCol =i.col
fig = make_subplots(
rows=maxRow,
cols=maxCol,
shared_xaxes=True,
vertical_spacing=0.02,
shared_yaxes=True,
horizontal_spacing=0.02,
#column_widths=[]
)
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_layout(barmode='relative')
for i in self.data:
if i.vtype=='Scatter':
fig.add_trace(go.Scatter(x=i.df['date'],y=i.df['value'],name=i.name), row=i.row, col=i.col)
elif i.vtype=='OCHL':
fig.add_trace(go.Candlestick(
x=i.df['date'],
open=i.df['open'],
high=i.df['high'],
low=i.df['low'],
close=i.df['close'],
name=i.name),
row=i.row, col=i.col
)
elif i.vtype=='Bars':
for j in i.df.keys():
if j!='date':
try:
colorType=i.colorType
except:
colorType='normal'
colors=self.getBarColorList(i.df[j],colorType)
fig.add_trace(go.Bar(x=i.df['date'], y=i.df[j],name=j,marker_color=colors))
ans=fig
if self.needShow:
plotly.offline.iplot(fig)
return ans

View File

@@ -0,0 +1,138 @@
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
class CoreMath:
def __init__(self, base_df, params={
'dataType':'ohcl',
'action': None,
'actionOptions':{}
}
):
self.base_df=base_df.reset_index(drop=True)
self.params=params
if self.params['dataType']=='ohcl':
self.col=self.base_df[self.params['actionOptions']['valueType']]
elif self.params['dataType']=='series':
self.col=self.base_df
self.ans=self.getAns()
def getAns(self):
ans=None
if self.params['action']=='findExt':
ans = self.getExtremumValue()
elif self.params['action']=='findMean':
ans = self.getMeanValue()
elif self.params['action']=='findSTD':
ans=self.getSTD()
return ans
def getExtremumValue(self):
ans=None
'''
actionOptions:
'extremumtype':
'min'
'max'
'valueType':
'open'
'close'
'high'
'low'
'''
if self.params['actionOptions']['extremumtype']=='max':
ans=max(self.col)
if self.params['actionOptions']['extremumtype']=='min':
ans=min(self.col)
return ans
def getMeanValue(self):
'''
actionOptions:
'MeanType':
'MA'
'SMA'
'EMA'
'WMA'
--'SMMA'
'valueType':
'open'
'close'
'high'
'low'
'window'
'span'
'weights'
'''
ans=None
if self.params['actionOptions']['MeanType']=='MA':
ans = self.col.mean()
if self.params['actionOptions']['MeanType']=='SMA':
ans=np.convolve(self.col, np.ones(self.params['actionOptions']['window']), 'valid') / self.params['actionOptions']['window']
#ans=self.col.rolling(window=self.params['actionOptions']['window']).mean().to_list()
if self.params['actionOptions']['MeanType']=='EMA':
ans=self.col.ewm(span=self.params['actionOptions']['span'], adjust=False).mean().to_list()
if self.params['actionOptions']['MeanType']=='WMA':
try:
weights=self.params['actionOptions']['weights']
except KeyError:
weights=np.arange(1,self.params['actionOptions']['window']+1)
ans=self.col.rolling(window=self.params['actionOptions']['window']).apply(lambda x: np.sum(weights*x) / weights.sum(), raw=False).to_list()
return(ans)
def getSTD(self):
'''
actionOptions:
window
'''
ans=None
try:
window=self.params['actionOptions']['window']
ans=np.asarray([])
for i in range(len(self.col)-window+1):
ans=np.append(ans,np.std(self.col[i:i+window], ddof=1))
except:
#window = len(self.col)
ans=np.std(self.col, ddof=1)
return ans

View File

@@ -0,0 +1,182 @@
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
import CoreTraidMath
import CoreDraw
init_notebook_mode()
class ADXI:
def __init__(self, base_df, options={
'dataType':'ohcl',
}, needFig=False,showOnlyIndex=True,drawFig=False):
self.base_df=base_df.reset_index(drop=True)
self.options=options
#self.norm_df=self.nornalize()
#self.col=col
#self.npCol=np.asarray(self.norm_df[self.col], dtype=np.float32)
#self.options=options
self.ans=self.getAns()
if needFig:
self.fig=self.pltShow(showOnlyIndex,drawFig)
def getDM(self):
#m,p=self.getMP()
dm_m=np.asarray([])
dm_p=np.asarray([])
tr=np.asarray([])
for i in range(1,self.base_df.shape[0]):
if (self.base_df['open'][i]>=
self.base_df['open'][i-1]):
dm_p=np.append(dm_p,self.base_df['open'][i]-self.base_df['open'][i-1])
else:
dm_p=np.append(dm_p,0)
if (self.base_df['close'][i]<=self.base_df['close'][i-1]):
dm_m=np.append(dm_m,self.base_df['close'][i-1]-self.base_df['close'][i])
else:
dm_m=np.append(dm_m,0)
tr=np.append(tr,
max(self.base_df['close'][i-1],self.base_df['high'][i])-
min(self.base_df['close'][i-1],self.base_df['low'][i]))
setattr(self,'dm_m',dm_m)
setattr(self,'dm_p',dm_p)
setattr(self,'tr',tr)
return dm_m,dm_p
def getEMA(self,Col):
ser = pd.Series(Col, copy=False)
op={'dataType':'series',
'action':'findMean',
'actionOptions':{'MeanType':'EMA','span':10}
}
ans=np.asarray(CoreTraidMath.CoreMath(ser,op).ans)
#print(ans)
#ans = np.asarray(ser.ewm(span=40,adjust=False).mean().to_list())
#print(ans)
#return(np.asarray(ser.ewm(span=40,adjust=False).mean().to_list()))
return ans
def getDI(self):
dm,dp=self.getDM()
dip=self.getEMA(dp/self.tr)
dim=self.getEMA(dm/self.tr)
return dim,dip
def getAns(self):
dim,dip=self.getDI()
np.seterr(invalid='ignore')
col=abs(np.true_divide((dim-dip),(dim+dip)))
setattr(self,'col',col)
adx=self.getEMA(col)
ans={
'DIM':dim*100,
'DIP':dip*100,
'ADX':adx*100
}
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['ADX'],'date':self.base_df['date'].to_list()[1:]}) ,
'row':row,
'col':1,
'name':'SenkouSpanB'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['DIP'],'date':self.base_df['date'].to_list()[1:]}) ,
'row':row,
'col':1,
'name':'+DI'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['DIM'],'date':self.base_df['date'].to_list()[1:]}) ,
'row':row,
'col':1,
'name':'-DI'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,114 @@
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 Alligator:
def __init__(self, base_df,options={}, 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 getMA(self,keyAns):
ans=None
op={'dataType':'ohcl',
'action':'findMean',
'actionOptions':{'MeanType':self.options[keyAns]['MeanType'],
'valueType':self.options['valueType'],
'window':self.options[keyAns]['window']}
}
ans=CoreTraidMath.CoreMath(self.base_df,op).ans
return ans
def getAns(self):
ans={'Jaw':{},
'Teeth':{},
'Lips':{}
}
for i in ans.keys():
ma=self.getMA(i)
ans[i]['y']=ma[:len(ma)-self.options[i]['shift']]
ans[i]['x']=self.base_df['date'][self.options[i]['window']+self.options[i]['shift']-1:]
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['Jaw']['y'],'date':self.ans['Jaw']['x']}) ,
'row':row,
'col':1,
'name':'Jaw'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['Teeth']['y'],'date':self.ans['Teeth']['x']}) ,
'row':row,
'col':1,
'name':'Teeth'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['Lips']['y'],'date':self.ans['Lips']['x']}) ,
'row':row,
'col':1,
'name':'Lips'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,108 @@
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 IDC:
def __init__(self, base_df,options={}, 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 getSMA(self,windowSMA):
return np.convolve(self.npCol, np.ones(int(windowSMA)), 'valid') / int(windowSMA)
def getAns(self):
ans={
'MaxExt':[],
'MinExt':[],
'x':[]
}
opMin={'dataType':'ohcl',
'action':'findExt',
'actionOptions':{'extremumtype':'min','valueType':'low'}
}
opMax={'dataType':'ohcl',
'action':'findExt',
'actionOptions':{'extremumtype':'max','valueType':'high'}
}
for i in range(self.options['window'],len(self.base_df)-self.options['shift']+1):
ans['MaxExt'].append(CoreTraidMath.CoreMath(self.base_df[i-self.options['window']:i],opMax).ans)
ans['x'].append(self.base_df['date'][i-1+self.options['shift']])
ans['MinExt'].append(CoreTraidMath.CoreMath(self.base_df[i-self.options['window']:i],opMin).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['MaxExt'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'MaxExt'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['MinExt'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'MinExt'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,124 @@
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 Envelopes:
def __init__(self, base_df,options={}, 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 getAns(self):
ans={
'MainEnv':[],
'PlusEnv':[],
'MinusEnv':[],
'x':[]
}
dictResp={}
dictResp['MeanType']=self.options['MeanType']
dictResp['valueType']=self.options['valueType']
try:
dictResp['window'] = self.options['window']
dictResp['span'] = self.options['window']
except:
pass
op={'dataType':'ohcl',
'action':'findMean',
'actionOptions':dictResp
}
if dictResp['MeanType']=='SMA':
y=CoreTraidMath.CoreMath(self.base_df,op).ans
ans['MainEnv']=y[:len(y)-self.options['shift']]
ans['PlusEnv']=ans['MainEnv']*(1+self.options['kProc']/100)
ans['MinusEnv']=ans['MainEnv']*(1-self.options['kProc']/100)
ans['x']=self.base_df['date'][self.options['window']-1+self.options['shift']:]
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['MainEnv'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'MainEnv'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['PlusEnv'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'PlusEnv'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['MinusEnv'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'MinusEnv'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,108 @@
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
import Ind_Alligator
class Gator:
def __init__(self, base_df,options={}, 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 getAns(self):
req=Ind_Alligator.Alligator(self.base_df,self.options).ans
#self.req=req
'''
ans={'Jaw-Teeth':{'y':[],'x':[]},
'Teeth-Lips':{'y':[],'x':[]},
}
JawTeethIter=self.options['Jaw']['window']+self.options['Jaw']['shift']-self.options['Teeth']['window']-self.options['Teeth']['shift']
TeethLipsIter=self.options['Teeth']['window']+self.options['Teeth']['shift']-self.options['Lips']['window']-self.options['Lips']['shift']
#print(TeethLipsIter)
for i in range(len(req['Jaw']['y'])):
ans['Jaw-Teeth']['y'].append(abs(req['Jaw']['y'][i]-req['Teeth']['y'][JawTeethIter+i]))
ans['Jaw-Teeth']['x']=req['Jaw']['x']
for i in range(len(req['Teeth']['y'])):
ans['Teeth-Lips']['y'].append(-abs(req['Teeth']['y'][i]-req['Lips']['y'][TeethLipsIter+i]))
ans['Teeth-Lips']['x']=req['Teeth']['x']
'''
ans={'Jaw-Teeth':[],
'Teeth-Lips':[],
'x':[]
}
JawTeethIter=self.options['Jaw']['window']+self.options['Jaw']['shift']-self.options['Teeth']['window']-self.options['Teeth']['shift']
TeethLipsIter=self.options['Teeth']['window']+self.options['Teeth']['shift']-self.options['Lips']['window']-self.options['Lips']['shift']
for i in range(len(req['Jaw']['y'])):
ans['Jaw-Teeth'].append(abs(req['Jaw']['y'][i]-req['Teeth']['y'][JawTeethIter+i]))
ans['Teeth-Lips'].append(-abs(req['Teeth']['y'][JawTeethIter+i]-req['Lips']['y'][JawTeethIter+TeethLipsIter+i]))
ans['x']=req['Jaw']['x']
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':'Bars',
'df':pd.DataFrame(
{'Jaw-Teeth':self.ans['Jaw-Teeth'],
'Teeth-Lips':self.ans['Teeth-Lips'],
'date':self.ans['x'].to_list()}
) ,
'row':row,
'col':1,
'name':'Gator',
'colorType':'diffAbs'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,188 @@
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
import CoreDraw
init_notebook_mode()
import CoreTraidMath
import plotly.express as px
class Ishimoku:
def __init__(self, base_df, options={
'dataType':'ohcl',
'short':9,
'middle':26,
'long':52,
'backstep':26,
'forwardstep':26
},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 getTankenSen(self):
y=np.asarray([])
x=np.asarray([])
for i in range(self.options['short'],self.base_df.shape[0]):
maxValue=max(self.base_df['high'][i-self.options['short']:i])
minValue=min(self.base_df['low'][i-self.options['short']:i])
y=np.append(y,(maxValue+minValue)*0.5)
x=np.append(x,self.base_df['date'][i])
#ts.append(max(self.base_df[self.options['colName']['high']][i-self.options['short']:i]))
ans={'y':y,'x':x}
return(ans)
def getKijunSen(self):
y=np.asarray([])
x=np.asarray([])
for i in range(self.options['middle'],self.base_df.shape[0]):
maxValue=max(self.base_df['high'][i-self.options['middle']:i])
minValue=min(self.base_df['low'][i-self.options['middle']:i])
y=np.append(y,(maxValue+minValue)*0.5)
x=np.append(x,self.base_df['date'][i])
#ts.append(max(self.base_df[self.options['colName']['high']][i-self.options['short']:i]))
ans={'y':y,'x':x}
return(ans)
def getChinkoSpan(self):
y=np.asarray(self.base_df['close'][self.options['backstep']:])
x=np.asarray(self.base_df['date'][:self.base_df.shape[0]-self.options['backstep']])
ans={'y':y,'x':x}
return(ans)
def getSenkouSpanA(self, data):
y=np.asarray([])
x=np.asarray([])
shift=len(data['TankenSen']['y'])-len(data['KijunSen']['y'])
for i in range(len(data['KijunSen']['x'])-self.options['forwardstep']):
y=np.append(y,(data['KijunSen']['y'][i]+data['TankenSen']['y'][i+shift])*0.5)
x=np.append(x,data['KijunSen']['x'][i+self.options['forwardstep']])
ans={'y':y,'x':x}
return(ans)
def getSenkouSpanB(self):
y=np.asarray([])
x=np.asarray([])
for i in range(self.options['long'],self.base_df.shape[0]-self.options['forwardstep']):
maxValue=max(self.base_df['high'][i-self.options['long']:i])
minValue=min(self.base_df['low'][i-self.options['long']:i])
y=np.append(y,(maxValue+minValue)*0.5)
x=np.append(x,self.base_df['date'][i+self.options['forwardstep']])
#ts.append(max(self.base_df[self.options['colName']['high']][i-sel
ans={'y':y,'x':x}
return(ans)
def getAns(self):
ans={}
ans['TankenSen']=self.getTankenSen()
ans['KijunSen']=self.getKijunSen()
ans['ChinkoSpan']=self.getChinkoSpan()
ans['SenkouSpanA']=self.getSenkouSpanA(ans)
ans['SenkouSpanB']=self.getSenkouSpanB()
#print(ans)
return(ans)
def pltShow(self,showOnlyIndex,drawFig):
ans=None
req=[]
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['TankenSen']['y'],'date':self.ans['TankenSen']['x']}) ,
'row':1,
'col':1,
'name':'TankenSen'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['KijunSen']['y'],'date':self.ans['KijunSen']['x']}) ,
'row':1,
'col':1,
'name':'KijunSen'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['ChinkoSpan']['y'],'date':self.ans['ChinkoSpan']['x']}) ,
'row':1,
'col':1,
'name':'ChinkoSpan'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['SenkouSpanA']['y'],'date':self.ans['SenkouSpanA']['x']}) ,
'row':1,
'col':1,
'name':'SenkouSpanA'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['SenkouSpanB']['y'],'date':self.ans['SenkouSpanB']['x']}) ,
'row':1,
'col':1,
'name':'SenkouSpanB'
})
if not showOnlyIndex:
req.append({
'vtype':'OCHL',
'df':self.base_df,
'row':1,
'col':1,
'name':'OHCL'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
#print(ans)
return ans

View File

@@ -0,0 +1,104 @@
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 LRI:
def __init__(self, base_df,options={}, needFig=False,showOnlyIndex=True,drawFig=False):
self.base_df=base_df.reset_index(drop=True)
self.options=options
self.col=self.base_df[self.options['valueType']]
self.ans=self.getAns()
if needFig:
self.fig=self.pltShow(showOnlyIndex,drawFig)
def getAns(self):
ans=None
l=np.asarray(list(range(len(self.col))))
k,b=np.polyfit(l,self.col,1)
setattr(self,'k',k)
setattr(self,'b',b)
b1=b+self.options['k']*pow(1-k*k,0.5)
b2=b-self.options['k']*pow(1-k*k,0.5)
ans={
'LRI':l*k+b,
'LRI+':l*k+b1,
'LRI-':l*k+b2,
'x':self.base_df['date']
}
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['LRI'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'LRI'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['LRI+'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'LRI+'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['LRI-'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'LRI-'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,88 @@
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 ISTD:
def __init__(self, base_df,options={}, 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 getAns(self):
ans=None
try:
op={'dataType':'ohcl',
'action':'findSTD',
'actionOptions':{
'valueType':self.options['valueType'],
'window':self.options['window']
}
}
x=self.base_df['date'][self.options['window']-1:].to_list()
except:
op={'dataType':'ohcl',
'action':'findSTD',
'actionOptions':{'valueType':self.options['valueType']}
}
x=self.base_df['date'].to_list()
y= CoreTraidMath.CoreMath(self.base_df,op).ans
ans={'y':y,'x':x}
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['y'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'ISTD'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,147 @@
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

View File

@@ -0,0 +1,109 @@
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 BB:
def __init__(self, base_df,options={}, 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 getAns(self):
ans={}
opMA={'dataType':'ohcl',
'action':'findMean',
'actionOptions':{
'MeanType':self.options['MeanType'],
'valueType':self.options['valueType'],
'window':self.options['window']
}
}
ans['BB']=CoreTraidMath.CoreMath(self.base_df,opMA).ans
opSTD={'dataType':'ohcl',
'action':'findSTD',
'actionOptions':{'valueType':self.options['valueType'],'window':self.options['window']}
}
ans['STD']=CoreTraidMath.CoreMath(self.base_df,opSTD).ans
ans['pSTD']=ans['BB']+ans['STD']*self.options['kDev']
ans['mSTD']=ans['BB']-ans['STD']*self.options['kDev']
ans['x']=np.array(self.base_df['date'][self.options['window']-1:].to_list())
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['BB'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'BB'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['pSTD'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'pSTD'
})
req.append({
'vtype':'Scatter',
'df':pd.DataFrame(
{'value':self.ans['mSTD'],'date':self.ans['x']}) ,
'row':row,
'col':1,
'name':'mSTD'
})
self.figDict=req
ans = CoreDraw.coreDraw(req,drawFig)
return ans

View File

@@ -0,0 +1,2 @@
Ind_Envelopes - SMA only

View File

@@ -0,0 +1,123 @@
from selenium import webdriver
import time
import pandas as pd
import requests
from bs4 import BeautifulSoup
import nest_asyncio
import asyncio
import requests_html as rh
import datetime
import pandas as pd
import json
def f_write(driver):
with open(r'C:\\BinOptions\\exemple_pars_tomorrow.txt', 'w',encoding="utf-8") as f:
f.write(driver.page_source)
def investingPars(path_file=None,dateDict=None):
ans=None
op=webdriver.FirefoxOptions()
#op.add_argument("--headless")
url='https://ru.investing.com/economic-calendar/'
#driver = webdriver.Firefox(executable_path='C:\\Users\\Redsandy\\Downloads\\geckodriver.exe')
EXE_PATH = r'C:\\Users\\Redsandy\\Downloads\\geckodriver.exe'
driver = webdriver.Firefox(executable_path=EXE_PATH,options=op)
try:
driver.get(url=url)
#time.sleep(5)
#driver.find_element_by_id('timeFrame_tomorrow').click()
#time.sleep(5)
#f_write(driver)
if dateDict!=None:
driver.find_element_by_id('datePickerToggleBtn').click()
driver.find_element_by_id("startDate").clear()
driver.find_element_by_id("startDate").send_keys(dateDict['startDate'])
driver.find_element_by_id("endDate").clear()
driver.find_element_by_id("endDate").send_keys(dateDict['endDate'])
#driver.find_element_by_id("startDate").send_keys("31/03/2022")
driver.find_element_by_id('applyBtn').click()
time.sleep(2)
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(2)
f_write(driver)
page_source=driver.page_source
except Exception as ex:
print(ex)
finally:
driver.close()
driver.quit()
path_file_csv=path_file
ans=getDF(page_source,path_file_csv)
return ans
def getTime(strok):
ans=None
if len(strok.text.split())==2:
ans = strok['title'].split()[-1]
else:
ans = strok.text
return ans
def getValat(strok):
ans=None
inc=0
for i in strok.find_all('i'):
if i['class'][0]=='grayFullBullishIcon':
inc=inc+1
ans= str(inc)+"/3"
return(ans)
def getUrl(strok):
ans=None
baseUrl='https://ru.investing.com'
ans=baseUrl+strok.find_all('a', href=True)[0]['href']
return ans
def getDF(doc,path_file):
ans=None
soup = BeautifulSoup(doc, 'html.parser')
tabl=soup.find("table", {"id": "economicCalendarData"}).find('tbody')
tdList=[]
buff=[]
for stats in tabl.find_all('tr'):
for row in stats.find_all('td'):
buff.append(row)
tdList.append(buff)
buff=[]
col_names=['Время', 'Валюта', 'Важность','Событие','URL', 'Факт.','Прогноз','Пред.','Date']
df= pd.DataFrame(columns=col_names)
for i in range(0, len(tdList)):
try:
if tdList[i][0]["class"][0]=='theDay':
colDate = tdList[i][0].text[:-3]
else:
newRow={
col_names[0]:getTime(tdList[i][0]),
col_names[1]:tdList[i][1].text.strip(),
col_names[2]:getValat(tdList[i][2]),
col_names[3]:tdList[i][3].text.strip(),
col_names[4]:getUrl(tdList[i][3]),
col_names[5]:tdList[i][4].text.strip(),
col_names[6]:tdList[i][5].text.strip(),
col_names[7]:tdList[i][6].text.strip(),
col_names[8]:colDate
}
df=df.append(newRow, ignore_index=True)
except:
pass
if path_file!=None:
df.to_csv(path_file, index=False, encoding='utf-8-sig')
return df

View File

@@ -0,0 +1,9 @@
dateDict={
'startDate':'30/03/2022',
'endDate':'01/04/2022'
}
p='C:\\BinOptions\\df_tomorrow.csv'
InvestCal.investingPars(p,dateDict)
or InvestCal.investingPars()

View File

@@ -0,0 +1,129 @@
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 market_trade.CoreTraidMath
import market_trade.CoreDraw
import market_trade.Ind_bollingerBands
import Siganls.coreSignal
class SignalB_B_1(Siganls.coreSignal):
def __init__(self,
IndDict={},
mode='retro',
):
super().__init__(name='1.1',mode=mode,target='nextBar',valeType='price')
self.IndDict=IndDict
self.BB=Ind_bollingerBands.BB(
IndDict['BB']['df'],
IndDict['BB']['params'],
IndDict['BB']['needFig'],
IndDict['BB']['showOnlyIndex'],
IndDict['BB']['drawFig']
)
self.getAns()
if mode=='retro':
self.analiz=self.analiz()
def getAns(self):
if self.mode=='retro':
df=self.BB.base_df#.set_index('date')
#print (df)
df_ind=pd.DataFrame.from_dict({
'date': self.BB.ans['x'],
'BB': self.BB.ans['BB'],
'pSTD': self.BB.ans['pSTD'],
'mSTD': self.BB.ans['mSTD'],
})
self.df_ind=df_ind
#df_ind=df_ind.set_index('date')
#print(df_ind)
dictSig={}
ans_sig=[]
analizLst=[]
difSize=len(df)-len(df_ind)
for i in range(len(df_ind)):
#print(df.iloc[i+dif]['date'],df_ind.iloc[i]['date'])
if df.iloc[i+difSize]['close'] >df_ind.iloc[i]['pSTD']:
ans_sig.append(1)
elif df.iloc[i+difSize]['close'] <df_ind.iloc[i]['mSTD']:
ans_sig.append(-1)
else:
ans_sig.append(0)
self.ans={
'signal':ans_sig,
'dttm':self.BB.ans['x']
}
return self.ans
def analiz(self):
df=self.BB.base_df
dictSig={}
ans_sig=self.ans['signal']
difSize=len(df)-len(self.df_ind)
analizLst=[]
for i in range(len(self.df_ind)-1):
if ans_sig[i]==1 and df.iloc[i+difSize]['close']<df.iloc[i+difSize+1]['high']:
analizLst.append(1)
elif ans_sig[i]==1 and df.iloc[i+difSize]['close']>=df.iloc[i+difSize+1]['low']:
analizLst.append(-1)
elif ans_sig[i]==-1 and df.iloc[i+difSize]['close']>df.iloc[i+difSize+1]['low']:
analizLst.append(1)
elif ans_sig[i]==-1 and df.iloc[i+difSize]['close']<=df.iloc[i+difSize+1]['high']:
analizLst.append(-1)
else:
analizLst.append(0)
self.analizLst=analizLst
t=0
f=0
zeroNum=0
for i in self.analizLst:
if i==1:
t=t+1
if i==-1:
f=f+1
if i==0:
zeroNum=zeroNum+1
ans={}
ans['chstota']=sum(self.analizLst)/len(self.analizLst)
ans['zeroNum %']=zeroNum/len(self.analizLst)
ans['t %']=t/len(self.analizLst)
ans['f %']=f/len(self.analizLst)
try:
ans['toch']=t/(t+f)
except:
pass
return ans

View File

@@ -0,0 +1,14 @@
class coreSignal():
def __init__ (self,
#indDict={},
name='NoName',
mode='retro',
target=None,
valeType=None
):
self.ans=None
self.name=name
#self.indDict=indDict
self.mode=mode
self.target=target # nextBar
self.valeType=valeType #price o c h l

View File

@@ -0,0 +1,13 @@
Signal_1
BB синал предсказывающий будет ли цена за следубщий бар больше\меньше цены закртыия текущего, если текущиий бар закрылся ниже\выше диапазона BB
ind_params={'MeanType':'SMA','window':5,'valueType':'low','kDev':2}
#df_candle[:3000],ind_params,True,False,True
indEl1={
'df':df_candle[:3000],
'params':ind_params,
'needFig':False,
'showOnlyIndex':False,
'drawFig':True
}
a=Signal_1.SignalB_B_1({'BB':indEl1})