tradingSystem/research/chip_absolute_all_20261030/chip_features.py

53 lines
2.8 KiB
Python
Raw Permalink Normal View History

"""只使用当日筹码分布识别上方稀疏与双峰低密度区。"""
import numpy as np
def runs(mask):
out=[];start=None
for i,v in enumerate(list(mask)+[False]):
if v and start is None:start=i
if not v and start is not None:out.append((start,i));start=None
return out
def chip_features(prices,percent,close):
p=np.asarray(prices,float);w=np.asarray(percent,float)
result={'chip_valid':False,'valley_evaluable':False,'chip_reason':'invalid_values'}
if len(p)<10 or close<=0 or not np.isfinite(close) or not np.isfinite(p).all() or not np.isfinite(w).all() or np.any(p<=0) or np.any(w<0):return result
if len(np.unique(p))!=len(p):result['chip_reason']='duplicate_prices';return result
order=np.argsort(p);p,w=p[order],w[order];mass=w.sum()
result['raw_mass']=float(mass)
if not 98<=mass<=102:result['chip_reason']='mass_out_of_range';return result
w=w/mass;r=p/close
upper=float(w[(r>=1.02)&(r<=1.12)].sum())
step=float(np.median(np.diff(p))/close)
result.update(chip_valid=True,chip_reason='OK',upper_mass=upper,upper_gap=bool(upper<=.05),
overhead=float(w[r>1].sum()),overhead_near15=float(w[(r>1)&(r<=1.15)].sum()),
overhead_far15=float(w[r>1.15].sum()),winner_from_dist=float(w[r<=1].sum()),
weighted_cost=float(np.sum(p*w)),peak_price=float(p[np.argmax(w)]),step_ratio=step,
valley_above=False,valley_crossing=False,valley_below=False,valley_width=0.,valley_depth=None,
valley_low=None,valley_high=None)
if step>.02:
result['chip_reason']='coarse_for_valley';return result
result['valley_evaluable']=True
edges=np.linspace(.5,1.5,101);centers=(edges[1:]+edges[:-1])/2
h=np.histogram(r,bins=edges,weights=w)[0]
smooth=np.convolve(h,[.25,.5,.25],mode='same')
peaks=[i for i in range(2,98) if .70<=centers[i]<=1.30 and smooth[i]>smooth[i-1] and smooth[i]>=smooth[i+1] and h[i-2:i+3].sum()>=.05]
valleys=[]
for left,right in zip(peaks[:-1],peaks[1:]):
peak_density=min(h[left],h[right])
if peak_density<=0:continue
threshold=.25*peak_density
for lo,hi in runs(h[left+1:right]<=threshold):
lo+=left+1;hi+=left+1
if hi-lo<5:continue
low,high=float(edges[lo]),float(edges[hi])
position='above' if low>=1.02-1e-10 else ('below' if high<=1 else ('crossing' if low<=1<high else 'near_above'))
result['valley_'+position]=True
valleys.append({'position':position,'low':low,'high':high,'depth':float(h[lo:hi].mean()/peak_density)})
above=[v for v in valleys if v['position']=='above']
if above:
v=min(above,key=lambda v:(v['low'],v['high']))
result.update(valley_low=v['low'],valley_high=v['high'],valley_width=v['high']-v['low'],valley_depth=v['depth'])
result['valleys']=valleys
return result