├── .DS_Store ├── .gitattributes ├── .gitignore ├── .idea ├── .gitignore ├── Stock-Data-Analysis-Prediction.iml ├── inspectionProfiles │ └── profiles_settings.xml ├── misc.xml ├── modules.xml ├── other.xml └── vcs.xml ├── README.md ├── image ├── .DS_Store ├── k-image.jpg └── priceChanging.jpg └── stock ├── .DS_Store ├── __init__.py ├── analysis ├── .DS_Store ├── __init__.py └── preprocess.py └── predict └── __init__.py /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/.DS_Store -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Default ignored files 3 | /workspace.xml -------------------------------------------------------------------------------- /.idea/Stock-Data-Analysis-Prediction.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 13 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/other.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Stock-Data-Analysis&Prediction 2 | 获取股票历史数据,并实现快速绘图。计算买入和卖出过程中的收益,并标记出涨跌转折点。最后,使用机器学习方法对数据进行建模,并给出股票未来走势的预测结果。 3 | 4 | ### 环境 5 | > Python 3.6 6 | > 7 | > Quandl 8 | - 免费的金融数据模块,50次/天访问请求(访客) 9 | - 从上市到至今的股票信息(更新不及时) 10 | > pandas_datareader(推荐) 11 | - 获得实时数据 12 | - 开盘价,最高价,最低价,收盘价,成交量,调整后的收盘价 13 | > mpl_finance 14 | > 15 | > fbprophet 16 | > 17 | ### 实现 18 | > 股票数据获取 19 | > 20 | >数据预处理 21 | > 22 | >股价涨跌变化 23 | > 24 | >股票走势预测 25 | 26 | ### k线图 27 | ![avatar](./image/k-image.jpg) 28 | ### 价格相对变化 29 | ![avatar](./image/priceChanging.jpg) -------------------------------------------------------------------------------- /image/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/image/.DS_Store -------------------------------------------------------------------------------- /image/k-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/image/k-image.jpg -------------------------------------------------------------------------------- /image/priceChanging.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/image/priceChanging.jpg -------------------------------------------------------------------------------- /stock/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/stock/.DS_Store -------------------------------------------------------------------------------- /stock/__init__.py: -------------------------------------------------------------------------------- 1 | import pandas_datareader as web 2 | import datetime 3 | import stock.analysis.preprocess as prep 4 | 5 | 6 | # 时间跨度 7 | end = datetime.datetime.now() 8 | start = end - 10 * datetime.timedelta(days=360) 9 | 10 | # 十年之内的交易数据 11 | df1 = web.DataReader('MSFT', 'yahoo', start, end) 12 | df2 = web.DataReader('AAPL', 'yahoo', start, end) 13 | # print(df1) 14 | arg = 'Close' 15 | 16 | anl = prep.Analysis('2018', df1, df2) 17 | result = anl.prePro(start, end) 18 | param = 'Close' 19 | # anl.showComp(arg, 'microsoft', 'apple') 20 | anl.showStock(result[0]) 21 | # anl.showKChart(result[0]) 22 | # anl.showDayCloseBarChart(result[0]) 23 | # anl.tradingStrategy(result[0]) 24 | # anl.buySale(result[0]) 25 | 26 | -------------------------------------------------------------------------------- /stock/analysis/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/stock/analysis/.DS_Store -------------------------------------------------------------------------------- /stock/analysis/__init__.py: -------------------------------------------------------------------------------- 1 | import stock.analysis.preprocess -------------------------------------------------------------------------------- /stock/analysis/preprocess.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | from mpl_finance import candlestick2_ohlc as ohlc 4 | 5 | 6 | class Analysis: 7 | def __init__(self, year, *df): 8 | self.df = df 9 | self.year = year 10 | self.whole_year = self.df[0][(self.year + '-01-01'):(self.year + '-12-31')] 11 | 12 | def isNull(self): 13 | for k in self.df: 14 | if k.isnull().values.sum(): 15 | return False 16 | return True 17 | 18 | # 数据清洗 19 | def dataClean(self): 20 | pass 21 | 22 | # 数据规范化 23 | def dataNorm(self, df): 24 | return (df - df.min()) / (df.max() - df.min()) 25 | 26 | def prePro(self, start_date, end_date): 27 | 28 | #  是否存在缺失值 29 | if self.isNull(): 30 | self.dataClean() 31 | 32 | return self.df 33 | 34 | # 两个股票的比较 35 | def showComp(self, arg, name1, name2): 36 | #  查看股票价格走势 37 | plt.figure(figsize=(18.5, 8.6)) # 设置图片大小 38 | # plot画图 39 | l1, = plt.plot(self.df[0][arg], 'b') 40 | l2, = plt.plot(self.df[1][arg], 'r') 41 | # 添加标题 42 | plt.title(f"comparison of {arg}", fontsize='15') 43 | plt.xlabel('year') # 添加x轴图标 44 | plt.ylabel('dollar') # 添加y轴图标 45 | # 设置图例 46 | plt.legend(handles=[l1, l2, ], labels=[f'{name1}', f'{name2}'], loc='best') 47 | plt.show() 48 | 49 | # 展示股票所有参数 50 | def showStock(self, df): 51 | # 归一化 52 | df = self.dataNorm(df) 53 | plt.style.use("seaborn-whitegrid") 54 | plt.figure(figsize=(18.5, 8.5)) 55 | 56 | plt.plot(df) 57 | plt.legend(labels=['High', 'Low', 'Open', 'Close', 'Volume', 'Adj-close'], loc='best') 58 | plt.show() 59 | 60 | # 展示股票k线图 61 | def showKChart(self, df): 62 | fig, ax = plt.subplots(figsize=(18.5, 8.5)) 63 | ohlc(ax, self.whole_year.Open, self.whole_year.High, self.whole_year.Low, self.whole_year.Close, 64 | width=0.5, alpha=0.6, colorup='r', colordown='g') 65 | plt.show() 66 | 67 | # 当日价格相对变化 68 | def showDayCloseLineChart(self, df): 69 | year_arg = self.whole_year.Close 70 | log_change = np.log(year_arg) - np.log(year_arg.shift(1)) 71 | 72 | fig, ax = plt.subplots(figsize=(18.5, 8.5)) 73 | ax.plot(log_change, ".-") 74 | ax.axhline(y=0, color='red', lw=1) 75 | plt.show() 76 | 77 | def showDayCloseBarChart(self, df): 78 | year_arg = self.whole_year.Close 79 | log_change = np.log(year_arg) - np.log(year_arg.shift(1)) 80 | 81 | # 柱状图 82 | fig, ax = plt.subplots(figsize=(30, 9)) 83 | log_change.plot(kind='bar') 84 | plt.show() 85 | 86 | # 股票交易策略 87 | ''' 88 | 而长期和短期变化曲线的交点,往往就是我们购入或卖出股票的时间点。如果我们是短期投资者,就可以建立一个交易策略。 89 | 当短期变化曲线从上方交与长期变化曲线,说明股票短期看跌,则卖出。 90 | 当短期变化曲线从下方交与长期变化曲线,说明股票长期看涨,则买入。 91 | ''' 92 | 93 | def tradingStrategy(self, df): 94 | year_arg = self.whole_year.Close 95 | # 短期和长期的平均变化 96 | short_rolling = year_arg.rolling(window=5).mean() 97 | long_rolling = year_arg.rolling(window=15).mean() 98 | 99 | fig, ax = plt.subplots(figsize=(16, 9)) 100 | ax.plot(year_arg.index, year_arg, label=f'{year} close') 101 | ax.plot(short_rolling.index, short_rolling, label='5 days rolling') 102 | ax.plot(long_rolling.index, long_rolling, label='20 days rolling') 103 | 104 | ax.set_xlabel('Date') 105 | ax.set_ylabel('Closing price ($)') 106 | 107 | ax.legend(fontsize='large') 108 | plt.show() 109 | 110 | def buySale(self, df): 111 | year_arg = self.whole_year.Close 112 | # 短期和长期的平均变化 113 | short_rolling = year_arg.rolling(window=5).mean() 114 | long_rolling = year_arg.rolling(window=15).mean() 115 | 116 | fig, ax = plt.subplots(figsize=(16, 9)) 117 | short_long = np.sign(short_rolling - long_rolling) 118 | buy_sell = np.sign(short_long - short_long.shift(1)) 119 | buy_sell.plot(ax=ax) 120 | ax.axhline(y=0, color='red', lw=2) 121 | plt.show() 122 | 123 | # 适合买入点 124 | buy_sell[buy_sell == 1] 125 | # 适合卖出点 126 | buy_sell[buy_sell == -1] 127 | 128 | print(year_arg[(self.year + '-05-16')] - year_arg[(self.year + '-05-13')]) 129 | -------------------------------------------------------------------------------- /stock/predict/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paulspaw/Stock-Data-Analysis-Prediction/c4af49ede75fec2872aa47a68a17136a525843b0/stock/predict/__init__.py --------------------------------------------------------------------------------