Skip to content

Commit

Permalink
Test Cache
Browse files Browse the repository at this point in the history
  • Loading branch information
JadenSWang committed May 8, 2020
1 parent 86eefcd commit e147d4e
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 53 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
dist/
dist/
MANIFEST
index.py
stock_wrapper/__cache__/
15 changes: 0 additions & 15 deletions Classes/JSONReader.py

This file was deleted.

Binary file removed Classes/__pycache__/JSONReader.cpython-37.pyc
Binary file not shown.
17 changes: 5 additions & 12 deletions Examples/example.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import stock_wrapper
from stock_wrapper import Stock

# getting the most updated prices requires a FREE robinhood account
stock_wrapper.robin.login('email', 'password')

apple = Stock('AAPL')
microsoft = Stock('MSFT')

apple.price # get the current price
microsoft.price

apple.history # get the entire history of the stock including Moving Averages
microsoft.history

# data analysis does NOT require a robinhood account
stock_wrapper.visualize.graph_trendline_analysis([apple, microsoft])
stock_wrapper.visualize.graph_candlestick_analysis([apple, microsoft])

portfolio = stock_wrapper.robin.build_portfolio()
portfolio.append(Stock('LYFT'))
portfolio.append(Stock('UBER'))
portfolio.append(Stock('AMD'))
portfolio.append(Stock('PYPL'))
portfolio.append(Stock('CSCO'))
# stock_wrapper.visualize.graph_trendline_analysis(portfolio)
# stock_wrapper.visualize.graph_candlestick_analysis(portfolio)
stock_wrapper.visualize.graph_candlestick_analysis([Stock('TSLA')])

stock_wrapper.visualize.graph_candlestick_analysis([Stock('SUN')])
Empty file added UAL.json
Empty file.
Binary file modified stock_wrapper/__pycache__/data.cpython-37.pyc
Binary file not shown.
Binary file modified stock_wrapper/__pycache__/visualize.cpython-37.pyc
Binary file not shown.
69 changes: 51 additions & 18 deletions stock_wrapper/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import yfinance
import robin_stocks
import pandas as pd
import os
import numpy as np

import json
import datetime

class data:
Expand All @@ -17,35 +19,36 @@ class data:
'max': 'max'
}

def __init__(self):
pass

@classmethod
def get_history(cls, ticker_symbol, calculate_averages=False):
def get_history(cls, ticker_symbol, calculate_averages=True, cache=True):
"""Takes in a ticker object and returns a pandas dataframe containing price,
:param stock: single Ticker Symbol
:type: str
:return: [list]: (timeframe <datetime.datetime>, price <int>)
"""
if cache and cls.cache.exists(ticker_symbol):
return pd.read_json(cls.cache.read_file(ticker_symbol))
else:
history = yfinance.Ticker(ticker_symbol).history(period='max').reset_index()
history['Average'] = (history['High'] + history['Low']) / 2

history = yfinance.Ticker(ticker_symbol).history(period='max').reset_index()
history['Average'] = (history['High'] + history['Low']) / 2
def __build_average(df, period):
name = (str(period) + '_SMA')

def __build_average(df, period):
name = (str(period) + '_SMA')
if len(history) > period:
history.loc[0:period, name] = 0

if len(history) > period:
history.loc[0:period, name] = 0
index = period + 1
while index < len(history):
history.iloc[index, history.columns.get_loc(name)] = history.iloc[index - period:index]['Close'].sum() / period
index += 1

index = period + 1
while index < len(history):
history.iloc[index, history.columns.get_loc(name)] = history.iloc[index - period:index]['Close'].sum() / period
index += 1
if calculate_averages:
__build_average(history, 50)
__build_average(history, 100)
__build_average(history, 200)

if calculate_averages:
__build_average(history, 50)
__build_average(history, 100)
__build_average(history, 200)
cls.cache.write_file(ticker_symbol, history.to_json())

return history

Expand All @@ -71,3 +74,33 @@ def get_historical_prices(cls, ticker_symbol, span='day'):
@staticmethod
def __get_time(time, conversion=-5):
return datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%SZ") + datetime.timedelta(hours=conversion)

@classmethod
def clear_cache(cls):
cls.cache.clear()

class cache:
@staticmethod
def read_file(ticker_name):
path = os.path.abspath('stock_wrapper/__cache__/' + ticker_name + '.py')
with open(path) as json_file:
data = json.load(json_file)

return data

@staticmethod
def write_file(ticker_name, data):
path = os.path.abspath('stock_wrapper/__cache__/' + ticker_name + '.py')
with open(path, 'w+') as outfile:
json.dump(data, outfile)

@staticmethod
def exists(ticker_name):
path = os.path.abspath('stock_wrapper/__cache__/' + ticker_name + '.py')
return os.path.exists(path)

@staticmethod
def clear():
dirpath = os.path.abspath('stock_wrapper/__cache__/')
for path in os.listdir(dirpath):
os.remove(os.path.abspath('stock_wrapper/__cache__/' + path))
12 changes: 5 additions & 7 deletions stock_wrapper/visualize.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@
from plotly.subplots import make_subplots

import threading
import multiprocessing as mp
import curses
import time
import datetime
import numpy as np


Expand Down Expand Up @@ -155,7 +153,7 @@ def __graph(stock):
plt.show()

@staticmethod
def graph_candlestick_analysis(stocks):
def graph_candlestick_analysis(stocks, cache=True):
"""Takes in a list of Ticker Symbols and optional span. Displays a matplot graph with the history of that stock, default span to one day
:param stock: list of Stock objects
:type stock: list [<stock_wrapper.Stock>]
Expand All @@ -167,7 +165,7 @@ def __graph(stock, data):
sns.set(style="darkgrid")

fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Candlestick(x=data['Date'], open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name='Market Price'))
fig.add_trace(go.Candlestick(x=data['Date'], open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], name=stock.ticker + 'Market Price'))
fig.add_trace(go.Scatter(x=data['Date'], y=data['50_SMA'], name='50 Day Moving Average', marker_color='rgba(13, 140, 214, .8)'))
fig.add_trace(go.Scatter(x=data['Date'], y=data['100_SMA'], name='100 Day Moving Average', marker_color='rgba(230, 223, 23, .8)'))
fig.add_trace(go.Scatter(x=data['Date'], y=data['200_SMA'], name='200 Day Moving Average', marker_color='rgba(255, 165, 0, .8)'))
Expand All @@ -177,13 +175,13 @@ def __graph(stock, data):

data = []
for stock in stocks:
data.append(stock_wrapper.data.get_history(stock.ticker, calculate_averages=True))
data.append(stock_wrapper.data.get_history(stock.ticker, calculate_averages=True, cache=cache))

for i in range(len(data)):
__graph(stocks[i], data[i])

@staticmethod
def graph_trendline_analysis(stocks):
def graph_trendline_analysis(stocks, cache):
"""Takes in a list of Ticker Symbols and optional span. Displays a matplot graph with the history of that stock, default span to one day
:param stock: list of Stock objects
:type stock: list [<stock_wrapper.Stock>]
Expand Down Expand Up @@ -214,7 +212,7 @@ def __graph(stock, data):

data = []
for stock in stocks:
data.append(stock_wrapper.data.get_history(stock.ticker, calculate_averages=True))
data.append(stock_wrapper.data.get_history(stock.ticker, calculate_averages=True, cache=cache))

for i in range(len(data)):
__graph(stocks[i], data[i])
Expand Down

0 comments on commit e147d4e

Please sign in to comment.