macd_test.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from jqdatasdk import *
  2. from sqlalchemy import create_engine
  3. from jqdatasdk.technical_analysis import *
  4. auth('18616891214', 'Ea?*7f68nD.dafcW34d!')
  5. import numpy as np
  6. import pandas as pd
  7. def calculateEMA(period, closeArray, ema, emaArray=[]):
  8. """计算指数移动平均"""
  9. length = len(closeArray)
  10. nanCounter = np.count_nonzero(np.isnan(closeArray))
  11. print('def ema', ema)
  12. if not emaArray:
  13. if not ema and ema:
  14. firstema = ema
  15. else:
  16. firstema = np.mean(closeArray[nanCounter:nanCounter + period - 1])
  17. # emaArray.extend(np.tile([np.nan], (nanCounter + period - 1)))
  18. print('fe', firstema)
  19. emaArray.append(firstema)
  20. for i in range(nanCounter, length):
  21. ema_a = (2 * closeArray[i] + (period - 1) * emaArray[-1]) / (period + 1)
  22. emaArray.append(ema_a)
  23. return np.array(emaArray[1:])
  24. def calculateMACD(closeArray,ema, shortPeriod=12, longPeriod=26, signalPeriod=9):
  25. ema12 = calculateEMA(shortPeriod, closeArray, ema, [])
  26. print(ema12)
  27. ema26 = calculateEMA(longPeriod, closeArray, ema, [])
  28. print(ema26)
  29. diff = ema12 - ema26
  30. dea = calculateEMA(signalPeriod, diff, 0, [])
  31. print(diff,len(diff))
  32. print('dea=', dea, type(dea))
  33. macd = 2 * (diff - dea)
  34. return macd, diff, dea
  35. stock = '300114.XSHE'
  36. fre = '1d'
  37. check_date = '2010-01-04'
  38. emaArray = []
  39. engine_stock = create_engine('mysql+pymysql://root:r6kEwqWU9!v3@localhost:3307/stocks?charset=utf8')
  40. df = pd.read_sql_query('select date,open,close,high,low,volume,money from `stk%s_%s`' % (stock, fre), engine_stock)
  41. df_close = df['close']
  42. ema = EMA(stock, check_date=f'2009-12-31', timeperiod=30)[stock]
  43. print('ddd', ema)
  44. df4 = calculateMACD(df_close, ema)
  45. # df2 = calculateMACD(emaArray, df_close)
  46. # print('df2=', df2)
  47. # print(len(df), len(df2[0]))
  48. # df3 = pd.concat([df, pd.Series(df2[0]).rename('macd'), pd.Series(df2[1]).rename('diff'), pd.Series(df2[2]).rename('dea')], axis=1)
  49. print('df=', df)
  50. df4 = pd.concat([df, pd.Series(df4[0]).rename('macd'), pd.Series(df4[1]).rename('diff'), pd.Series(df4[2]).rename('dea')], axis=1)
  51. print('df=', df4)
  52. print(df4.loc[df.date== '2010-09-10',:])
  53. x_macd_dif, x_macd_dea, x_macd_macd = MACD(stock, check_date='2010-09-13 00:00:00', SHORT=12, LONG=26, MID=9, unit=fre)
  54. print(x_macd_macd, x_macd_dif, x_macd_dea)