-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
198 lines (157 loc) · 4.84 KB
/
main.py
File metadata and controls
198 lines (157 loc) · 4.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
import sqlite3
from sqlite3 import Error
import csv
import numpy as np
import tempfile
import streamlit as st
import io
import yfinance as yf
import pandas as pd
import datetime
import time
import pandas_datareader.data as web
import sqlalchemy
from datetime import datetime, timedelta
uploaded_file = st.file_uploader(...)
conn = None
db = st.file_uploader("stock.db", type="db")
if db:
with tempfile.NamedTemporaryFile() as fp:
fp.write(db.getvalue())
conn = sqlite3.connect(fp.name)
if conn:
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
def create_project(conn, project):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO projects(compamy_name,begin_price,end_price)
Values(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, project)
conn.commit()
return cur.lastrowid
def create_task(conn, task):
"""
Create a new task
:param conn:
:param task:
:return:
"""
sql = ''' INSERT INTO tasks(name,priority,status_id,project_id,begin_date,end_date)
VALUES(?,?,?,?,?,?) '''
cur = conn.cursor()
cur.execute(sql, task)
conn.commit()
return cur.lastrowid
def main():
database = r"./stock.db"
conn = create_connection(database)
with conn:
try:
curs = conn.cursor()
curs.execute('''CREATE TABLE IF NOT EXISTS stock (
id INT PRIMARY KEY,
company_name VARCHAR(200),
now_price INT
)''')
curs.close()
except:
import traceback
print(traceback.format_exc())
from csv import DictReader
with open('data.csv', encoding='utf-8-sig') as file:
data = DictReader(file)
curs = conn.cursor()
for row in data:
print(row)
ins = 'INSERT INTO stock (id, company_name, now_price) VALUES (?, ?, ?)'
curs.execute(ins, (
row['id'],
row['company_name'],
int(row['now_price'])
))
ticker = 'AAPL', 'TSLA'
def make_connection(db_file):
""" create a database connection to the SQLite database
specified by the db file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
except Error as e:
print(e)
return conn
start_time = datetime.datetime(2019, 9, 1)
end_time = datetime.datetime.now().date().isoformat()
connected = False
while not connected:
try:
df = web.get_data_yahoo(ticker, start=start_time, end=end_time)
connected = True
print('connected to yahoo')
except Exception as e:
print("type error: " + str(e))
time.sleep(3)
pass
con = sqlalchemy.create_engine('sqlite"///stock.db')
con.execute('''DROP TABLE stock_hist''')
pd.read_sql_table('stock', con)
con.execute('''
CREATE TABLE stock_hist(
date TIMESTAMP,
company VARCHAR(100),
high INTEGER,
low INTEGER,
open INTEGER,
close INTEGER,
volume INTEGER,
adjclose INTEGER,
PRIMARY KEY (date, company)
''')
companies = ['AAPL', 'TSLA', 'BRK-B', 'DIS', 'AMZN', 'WMT', 'COST', 'AMAT']
end = datetime.now()
start = end - timedelta(days=365)
df = web.get_data_yahoo(companies, start=start, end=end)
for date, item in df.iterrows():
for company in companies:
high = item.High[company]
low = item.Low[company]
open_val = item.Open[company]
close = item.Close[company]
volume = item.Volume[company]
adjclose = item['Adj Close'][company]
try:
con.execute('''
INSERT INTO stock_hist(date, company, high, low, open, close, volume, adjclose)
values(:date, :company, :high, :low, :open, :close, :volume, :adjclose)
''', dict(
date = date.to_pydatetime(),
company=company,
high=high,
low=low,
open=open_val,
close=close,
volume=volume,
adjclose=adjclose
))
except sqlalchemy.exc.IntegerityError as e:
pass
if __name__ == '__main__':
main()