· 6 years ago · Apr 01, 2019, 05:04 PM
1https://we.tl/t-7HUMir8bku
2
3
4
5from django.shortcuts import render
6from django.http import Http404
7from rest_framework.views import APIView
8from rest_framework.decorators import api_view
9from rest_framework.response import Response
10from rest_framework import status
11from django.http import JsonResponse
12from django.core import serializers
13from django.conf import settings
14from Stock.settings import STATIC_DIR;
15import json
16import os
17import csv
18import numpy as np
19from sklearn import linear_model
20import matplotlib.pyplot as plt
21
22@api_view(["POST"])
23def IdealWeight(heightdata):
24 try:
25 height=json.loads(heightdata.body)
26 weight=str(TestBro(height))
27
28 return JsonResponse("Ideal weight id "+weight+"kg",safe=False)
29 except ValueError as e:
30 return Response(e.args[0],status.HTTP_404_BAD_REQUEST)
31
32
33
34def TestBro(x):
35
36 return (x*5)
37
38
39@api_view(["GET"])
40def stock(self):
41 a=29
42 dates = []
43 prices = []
44 datessec=[]
45 pricesec=[]
46 year=[]
47 year_price=[]
48
49
50
51 filename=os.path.join(STATIC_DIR,'data.csv')
52 with open(filename,'r') as csvfile:
53 csvFileReader = csv.reader(csvfile)
54 next(csvFileReader) #skipping column names
55 for row in csvFileReader:
56 dates.append(int(row[0]))
57 prices.append(float(row[1]))
58 #year.append(int(row[2]))
59 #year_price.append(float(row[1]))
60
61
62 predicted_price= predict_price(dates,prices,a)
63
64
65 filename=os.path.join(STATIC_DIR,'datasec.csv')
66 with open(filename,'r') as csvfile:
67 csvFileReader = csv.reader(csvfile)
68 next(csvFileReader) #skipping column names
69 for row in csvFileReader:
70 datessec.append(int(row[0]))
71 pricesec.append(float(row[1]))
72 #year.append(int(row[2]))
73 #year_price.append(float(row[1]))
74
75 predicted_price_sec= predict_price(dates,prices,a)
76
77 filename=os.path.join(STATIC_DIR,'year.csv')
78 with open(filename,'r') as csvfile:
79 csvFileReader = csv.reader(csvfile)
80 next(csvFileReader) #skipping column names
81 for row in csvFileReader:
82 year.append(int(row[0]))
83 year_price.append(float(row[1]))
84 #year.append(int(row[2]))
85
86 dict={'predicted_price':predicted_price, 'date_list': dates,'price_list':prices,'date_list_sec':datessec,'price_list_sec':pricesec,'predicted_price_sec':predicted_price_sec,'year': year,'year_price':year_price}
87 return JsonResponse(dict,safe=False)
88
89@api_view(["GET"])
90def stockyear(self):
91 year=[]
92 year_price=[]
93 filename=os.path.join(STATIC_DIR,'data.csv')
94 with open(filename,'r') as csvfile:
95 csvFileReader = csv.reader(csvfile)
96 next(csvFileReader) #skipping column names
97 for row in csvFileReader:
98 year.append(int(row[0]))
99 year_price.append(float(row[1]))
100 #year.append(int(row[2]))
101 #year_price.append(float(row[1]))
102
103
104 dict={'year': year,'year_price':year_price}
105 return JsonResponse(dict,safe=False)
106
107
108
109def predict_price(dates,prices,a):
110 linear_mod = linear_model.LinearRegression() #defining the linear regression model
111 dates = np.reshape(dates,(len(dates),1)) # converting to matrix of n X 1
112 prices = np.reshape(prices,(len(prices),1))
113 linear_mod.fit(dates,prices) #fitting the data points in the model
114 predicted_price =linear_mod.predict(a)
115 return predicted_price[0][0]
116
117
118@api_view(["POST"])
119def prediction(height):
120 dates = []
121 prices = []
122 filename=os.path.join(STATIC_DIR,'data.csv')
123 with open(filename,'r') as csvfile:
124 csvFileReader = csv.reader(csvfile)
125 next(csvFileReader) #skipping column names
126 for row in csvFileReader:
127 dates.append(int(row[0]))
128 prices.append(float(row[1]))
129
130 linear_mod = linear_model.LinearRegression() #defining the linear regression model
131 dates = np.reshape(dates,(len(dates),1)) # converting to matrix of n X 1
132 prices = np.reshape(prices,(len(prices),1))
133 linear_mod.fit(dates,prices) #fitting the data points in the model
134 predicted_price =linear_mod.predict(height)
135 return JsonResponse(predicted_price[0][0],safe=False)
136
137
138
139
140
141from django.conf.urls import url
142from django.contrib import admin
143from MyStockApp import views
144
145urlpatterns = [
146 url(r'^admin/', admin.site.urls),
147 url(r'^IdealWeight/', views.IdealWeight),
148 url(r'^prediction/', views.prediction),
149 url(r'^stock/', views.stock)
150
151]
152
153
154
155
156
157
158
159
160"""
161Django settings for Stock project.
162
163Generated by 'django-admin startproject' using Django 2.1.7.
164
165For more information on this file, see
166https://docs.djangoproject.com/en/2.1/topics/settings/
167
168For the full list of settings and their values, see
169https://docs.djangoproject.com/en/2.1/ref/settings/
170"""
171
172import os
173
174# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
175BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
176STATIC_DIR= os.path.join(BASE_DIR,'static')
177
178# Quick-start development settings - unsuitable for production
179# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
180
181# SECURITY WARNING: keep the secret key used in production secret!
182SECRET_KEY = '5=cun55(ks8@_#@zwa+7@mcs&6^i++r-e$5dg1v5_xgx$gr5ad'
183
184# SECURITY WARNING: don't run with debug turned on in production!
185DEBUG = True
186
187ALLOWED_HOSTS = []
188
189
190# Application definition
191
192INSTALLED_APPS = [
193 'django.contrib.admin',
194 'django.contrib.auth',
195 'django.contrib.contenttypes',
196 'django.contrib.sessions',
197 'django.contrib.messages',
198 'django.contrib.staticfiles',
199 'rest_framework',
200 'MyStockApp' ,
201 'corsheaders'
202]
203
204MIDDLEWARE = [
205 'django.middleware.security.SecurityMiddleware',
206 'django.contrib.sessions.middleware.SessionMiddleware',
207 'corsheaders.middleware.CorsMiddleware',
208 'django.middleware.common.CommonMiddleware',
209 'django.middleware.csrf.CsrfViewMiddleware',
210 'django.contrib.auth.middleware.AuthenticationMiddleware',
211 'django.contrib.messages.middleware.MessageMiddleware',
212 'django.middleware.clickjacking.XFrameOptionsMiddleware',
213]
214
215ROOT_URLCONF = 'Stock.urls'
216
217ALLOWED_HOSTS = ['192.168.0.107']
218
219TEMPLATES = [
220 {
221 'BACKEND': 'django.template.backends.django.DjangoTemplates',
222 'DIRS': [],
223 'APP_DIRS': True,
224 'OPTIONS': {
225 'context_processors': [
226 'django.template.context_processors.debug',
227 'django.template.context_processors.request',
228 'django.contrib.auth.context_processors.auth',
229 'django.contrib.messages.context_processors.messages',
230 ],
231 },
232 },
233]
234
235WSGI_APPLICATION = 'Stock.wsgi.application'
236
237
238# Database
239# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
240
241DATABASES = {
242 'default': {
243 'ENGINE': 'django.db.backends.sqlite3',
244 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
245 }
246}
247
248
249# Password validation
250# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
251
252AUTH_PASSWORD_VALIDATORS = [
253 {
254 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
255 },
256 {
257 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
258 },
259 {
260 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
261 },
262 {
263 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
264 },
265]
266
267
268# Internationalization
269# https://docs.djangoproject.com/en/2.1/topics/i18n/
270
271LANGUAGE_CODE = 'en-us'
272
273TIME_ZONE = 'UTC'
274
275USE_I18N = True
276
277USE_L10N = True
278
279USE_TZ = True
280
281
282# Static files (CSS, JavaScript, Images)
283# https://docs.djangoproject.com/en/2.1/howto/static-files/
284
285STATIC_URL = '/static/'
286
287CORS_ORIGIN_WHITELIST='localhost:8000/stock/'
288CORS_ORIGIN_WHITELIST='192.168.0.107:8000/stock/'
289
290
291
292
293 WebView webView;
294 @Override
295 protected void onCreate(Bundle savedInstanceState) {
296 super.onCreate(savedInstanceState);
297 setContentView(R.layout.activity_main);
298
299 webView= (WebView) findViewById(R.id.webViewUi);
300 webView.clearCache(true);
301 webView.getSettings().setJavaScriptEnabled(true);
302
303 webView.getSettings().setAllowFileAccess(true);
304 webView.loadUrl("http://192.168.0.107/Sentiment/test.html");
305
306
307
308
309 webView.setWebViewClient(new WebViewClient());
310
311
312
313 }
314
315
316
317
318 <WebView
319 android:layout_width="match_parent"
320 android:layout_height="match_parent"
321 android:layout_alignParentTop="true"
322 android:layout_alignParentStart="true"
323 android:id="@+id/webViewUi" />