Skip to content

Commit 7f9f133

Browse files
committed
数字货币行情获取和指标计算演示
1 parent bb1a969 commit 7f9f133

File tree

4 files changed

+158
-0
lines changed

4 files changed

+158
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__pycache__/

MyTT.py

+111
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# MyTT 麦语言-通达信-同花顺指标实现 https://github.com/mpquant/MyTT
2+
3+
import numpy as np; import pandas as pd
4+
5+
6+
def RD(N,D=3): return np.round(N,D) #四舍五入取3位小数
7+
def RET(S,N=1): return np.array(S)[-N] #返回序列倒数第N个值,默认返回最后一个
8+
def ABS(S): return np.abs(S) #返回N的绝对值
9+
def MAX(S1,S2): return np.maximum(S1,S2) #序列max
10+
def MIN(S1,S2): return np.minimum(S1,S2) #序列min
11+
12+
def MA(S,N): #求序列的N日平均值,返回序列
13+
return pd.Series(S).rolling(N).mean().values
14+
15+
def REF(S, N=1): # 对序列整体下移动N,返回序列(shift后会产生NAN)
16+
return pd.Series(S).shift(N).values
17+
18+
def DIFF(S, N=1): #前一个值减后一个值,前面会产生nan
19+
return pd.Series(S).diff(N) #np.diff(S)直接删除nan,会少一行
20+
21+
def STD(S,N): #求序列的N日标准差,返回序列
22+
return pd.Series(S).rolling(N).std(ddof=0).values
23+
24+
def IF(S_BOOL,S_TRUE,S_FALSE): # res=S_TRUE if S_BOOL==True else S_FALSE
25+
return np.where(S_BOOL, S_TRUE, S_FALSE)
26+
27+
def SUM(S, N): #对序列求N天累计和,返回序列
28+
return pd.Series(S).rolling(N).sum().values
29+
30+
def HHV(S,N): # HHV(C, 5) # 最近5天收盘最高价
31+
return pd.Series(S).rolling(N).max().values
32+
33+
def LLV(S,N): # LLV(C, 5) # 最近5天收盘最低价
34+
return pd.Series(S).rolling(N).min().values
35+
36+
def EMA(S,N): #为了精度 S>4*N EMA至少需要120周期
37+
return pd.Series(S).ewm(span=N, adjust=False).mean().values
38+
39+
def SMA(S, N, M=1): #中国式的SMA,至少需要120周期才精确
40+
K = pd.Series(S).rolling(N).mean() #先求出平均值
41+
for i in range(N+1, len(S)): K[i] = (M * S[i] + (N -M) * K[i-1]) / N # 因为要取K[i-1],所以 range(N+1, len(S))
42+
return K
43+
44+
def AVEDEV(S,N): # 平均绝对偏差 (序列与其平均值的绝对差的平均值)
45+
avedev=pd.Series(S).rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean())
46+
return avedev.values
47+
#--------------------------------------------------------------------
48+
49+
def COUNT(S_BOOL, N): # COUNT(C>O, N): 最近N天满足S_BOO的天数 True的天数
50+
return SUM(S_BOOL,N)
51+
52+
def EVERY(S_BOOL, N): # EVERY(C>O, 5) 最近N天是否都是True
53+
R=SUM(S_BOOL, N)
54+
return IF(R==N, True, False)
55+
56+
def EXIST(S_BOOL, N=5): # EXIST(CLOSE>3010, N=5) n日内是否存在一天大于3000点
57+
R=SUM(S_BOOL,N)
58+
return IF(R>0, True ,False)
59+
60+
def CROSS(S1,S2): # 判断穿越 CROSS(MA(C,5),MA(C,10))
61+
CROSS_BOOL=IF(S1>S2, True ,False) #;print(CROSS_BOOL)
62+
return COUNT(CROSS_BOOL>0,2)==1 # 上穿:昨天0 今天1 下穿:昨天1 今天0
63+
64+
#-----------------------------------下面是具体指标-------------------------------------
65+
def MACD(CLOSE,SHORT=12,LONG=26,M=9): # EMA的关系,S取120日,和雪球小数点2位相同
66+
DIF = EMA(CLOSE,SHORT)-EMA(CLOSE,LONG);
67+
DEA = EMA(DIF,M); MACD=(DIF-DEA)*2
68+
return RD(DIF),RD(DEA),RD(MACD)
69+
70+
def KDJ(CLOSE,HIGH,LOW, N=9,M1=3,M2=3):
71+
RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100
72+
K = EMA(RSV, (M1*2-1)); D = EMA(K,(M2*2-1)); J=K*3-D*2
73+
return K, D, J
74+
75+
def RSI(CLOSE, N=24):
76+
DIF = CLOSE-REF(CLOSE,1)
77+
return RD(SMA(MAX(DIF,0), N) / SMA(ABS(DIF), N) * 100)
78+
79+
def WR(CLOSE, N=10, N1=6): #W&R 威廉指标
80+
WR = (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) * 100
81+
WR1 = (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) * 100
82+
return RD(WR), RD(WR1)
83+
84+
def BIAS(CLOSE,L1=6, L2=12, L3=24): # BIAS乖离率
85+
BIAS1 = (CLOSE - MA(CLOSE, L1)) / MA(CLOSE, L1) * 100
86+
BIAS2 = (CLOSE - MA(CLOSE, L2)) / MA(CLOSE, L2) * 100
87+
BIAS3 = (CLOSE - MA(CLOSE, L3)) / MA(CLOSE, L3) * 100
88+
return RD(BIAS1), RD(BIAS2), RD(BIAS3)
89+
90+
def BOLL(CLOSE,N=20, P=2): #BOLL布林带
91+
MID = MA(CLOSE, N);
92+
UPPER = MID + STD(CLOSE, N) * P
93+
LOWER = MID - STD(CLOSE, N) * P
94+
return RD(UPPER), RD(MID), RD(LOWER)
95+
96+
def PSY(CLOSE,N=12, M=6):
97+
PSY=COUNT(CLOSE>REF(CLOSE,1),N)/N*100
98+
PSYMA=MA(PSY,M)
99+
return RD(PSY),RD(PSYMA)
100+
101+
102+
def CCI(CLOSE,HIGH,LOW,N=14):
103+
TP=(HIGH+LOW+CLOSE)/3
104+
return (TP-MA(TP,N))/(0.015*AVEDEV(TP,N))
105+
106+
def ATR(CLOSE,HIGH,LOW, N=20): #真实波动N日平均值
107+
TR = MAX(MAX((HIGH - LOW), ABS(REF(CLOSE, 1) - HIGH)), ABS(REF(CLOSE, 1) - LOW))
108+
return MA(TR, N)
109+
110+
111+

example1.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#数字货币行情获取和指标计算演示
2+
from hb_hq_api import *
3+
from MyTT import *
4+
5+
6+
df=get_price('btc.usdt',count=120,frequency='1d'); #日线数据获取 1d:1天 4h:4小时 60m: 60分钟 15m:15分钟
7+
CLOSE=df.close.values; OPEN=df.open.values; HIGH=df.high.values; LOW=df.low.values #基础数据定义
8+
9+
MA5=MA(CLOSE,5)
10+
MA10=MA(CLOSE,10)
11+
CROSS_TODAY=RET(CROSS(MA5,MA10))
12+
13+
print(f'BTC5日均线{ MA5[-1]} BTC10日均线 {MA10[-1]}' )
14+
print('今天5日线是否上穿10日线',CROSS_TODAY)
15+
print('最近5天收盘价全都大于5日线吗?',EVERY(CLOSE>MA10,5) )
16+
17+
DIF,DEA,MACD=MACD(CLOSE)
18+
print('MACD值',DIF,DEA,MACD)

hb_hq_api.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#火币行情功能函数
2+
import json,requests,urllib3,datetime; import pandas as pd; import numpy as np ; urllib3.disable_warnings()
3+
4+
huobi_domain='api.huobi.de.com' #API地址 'api.huobi.pro' api.huobi.be没有被墙 api.huobi.de.com
5+
6+
class Context: #根类
7+
def __init__(self):
8+
self.current_dt=datetime.datetime.now()
9+
10+
# #1d:1天 4h:4小时 60m: 60分钟 15m:15分钟
11+
def get_price(code, end_date=None, count=1,frequency='1d', fields=['close']):
12+
code=code.replace('.','')
13+
frequency=frequency.replace('d','day').replace('m','min').replace('h','hour')
14+
url = f'https://{huobi_domain}/market/history/kline?period={frequency}&size={count}&symbol={code}'
15+
res = requests.get(url,verify=False).text
16+
df=pd.DataFrame(json.loads(res)['data']); df=df.iloc[::-1] #排序翻转
17+
df["time"] = pd.to_datetime(df["id"]+8*3600, unit='s') #时间戳转时间,北京时间+8小时
18+
df=df[['time','open','close','high','low','vol']] #更正排序
19+
df.set_index(["time"], inplace=True); df.index.name='' #处理索引
20+
return df
21+
22+
def get_last_price(code): #获取某只股票最新价格函数04-25
23+
return get_price(code,count=1,frequency='1m', fields=['close']).close[0]
24+
25+
def attribute_history(security, count, unit='1d', fields=['open', 'close', 'high', 'low', 'volume', 'money']): #获取历史行情
26+
return get_price(security = security, end_date = context.current_dt, frequency=unit, fields=fields, fq = fq, count = count)[:-1]
27+
28+

0 commit comments

Comments
 (0)