Files
Stock/pandas_eval.py
T
jens f6b3ed673c - fixed
git-svn-id: http://moon:8086/svn/projects/Stock@299 fda53097-d464-4ada-af97-ba876c37ca34
2019-12-10 07:46:08 +00:00

142 lines
2.8 KiB
Python

import pandas as pd
import pandas_datareader.data as web
import numpy as np
import math
import matplotlib.pyplot as plt
import datetime
# Stock Investors Financial Math
# https://www.fmlabs.com/reference/default.htm?url=SimpleMA.htm
# Alpha Vantage
# https://www.alphavantage.co/documentation/
# Pandas
# https://pandas.pydata.org/pandas-docs/stable/index.html
# Knowledge
# https://www.investopedia.com/articles/technical/02/050602.asp
# https://ntguardian.wordpress.com/2016/09/19/introduction-stock-market-data-python-1
key = '0UO7Z2MVZ2YSQSVE'
def ema(data, key, alpha=0.5, ic=None):
result = []
if ic is None:
r = data[key][0]
else:
r = ic
for v in data[key]:
r = alpha*r + (1-alpha)*v
result.append(r)
return np.array(result)
def sma(data, key, window_days, ic=None):
mem = [0] * window_days
result = []
k=0
cumsum = 0
for v in data[key]:
cumsum += (v - mem[k])
mem[k] = v
k += 1
if k >= window_days:
k=0
result.append(cumsum/window_days)
return result
def sd(data, key, window_days, ic=None):
mem = [0] * window_days
result = []
k=0
cumsum = 0
data_mean = data[key] - sma(data, key, window_days, ic)
for v in data_mean:
v2 = v * v
cumsum += (v2 - mem[k])
mem[k] = v2
k += 1
if k >= window_days:
k=0
var = max(0, cumsum) / window_days
result.append(math.sqrt(var))
return result
def colsum(data, keys):
result = np.zeros(data.shape[0])
for key in keys:
result += data[key]
return result
def macd(data, key):
ema_short = ema(data, key, alpha=0.85)
ema_long = ema(data, key, alpha=0.925)
return ema_short - ema_long
def bollinger(data, window_days, f=2):
tp_ser = colsum(data, keys=['high', 'low', 'close']) / 3
tp_df = tp_ser.to_frame(name='tp')
stddev = np.array(sd(tp_df, 'tp', window_days))
mid = np.array(sma(tp_df, key='tp', window_days=window_days))
upper = mid + f * stddev
lower = mid - f * stddev
result = pd.DataFrame(upper, index=data.index, columns=['upper'])
result['lower'] = lower
result['mid'] = mid
return result
data = {}
title = 'AAPL'
if 0:
# Get stock price via data reader
start = datetime.datetime(2016,1,1)
end = datetime.date.today()
data = web.DataReader(title, "av-daily", start, end, api_key=key)
# data = web.DataReader(title, "stooq", start, end)
print(data)
hdf = pd.HDFStore(title + '.h5')
hdf[title] = data
else:
hdf = pd.HDFStore(title + '.h5', 'r')
data = hdf[title]
data['ema'] = ema(data, key='close', alpha=0.75)
data['macd'] = macd(data, key='close')
data['sma'] = sma(data, key='close', window_days=30)
boll = bollinger(data, window_days=30)
plt.subplot(311)
data['close'].plot()
data['ema'].plot()
data['sma'].plot()
plt.legend()
plt.grid()
plt.subplot(312)
boll['upper'].plot()
boll['mid'].plot()
boll['lower'].plot()
plt.legend()
plt.grid()
plt.subplot(313)
data['macd'].plot()
plt.legend()
plt.grid()
plt.show()
hdf.close()