Arafath10 commited on
Commit
58d4ba4
1 Parent(s): 9850ead

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +117 -68
main.py CHANGED
@@ -1,86 +1,135 @@
1
- from fastapi import FastAPI, File, UploadFile
2
- from fastapi.responses import FileResponse
3
- import os
4
- import io
5
- from fastapi.middleware.cors import CORSMiddleware
6
  import requests
 
 
 
 
7
  import pandas as pd
8
-
 
 
 
 
9
 
10
  app = FastAPI()
 
 
 
 
 
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
- allow_origins=["*"],
14
  allow_credentials=True,
15
- allow_methods=["*"],
16
- allow_headers=["*"],
17
  )
18
- # Parameters
19
- API_KEY = "an3vib2nh4-3R48tMWfBZg"
20
- WEBSITE_COLUMN = "Website"
21
 
 
 
 
 
22
 
 
 
 
 
 
 
23
 
24
- def get_company_data(api_key, domain):
25
- response = requests.get(f"https://api.apollo.io/v1/organizations/enrich?api_key={api_key}&domain={domain}")
26
- result = response.json()
27
 
28
- if "organization" in result:
29
- org = result["organization"]
30
- return {
31
- "domain": domain,
32
- "alexa_ranking": org.get("alexa_ranking", "unknown"),
33
- "annual_revenue": org.get("annual_revenue", "unknown"),
34
- "country": org.get("country", "unknown"),
35
- "estimated_num_employees": org.get("estimated_num_employees", "unknown"),
36
- "industry": org.get("industry", "unknown"),
37
- "keywords": org.get("keywords", "unknown"),
38
- "linkedin_uid": org.get("linkedin_uid", "unknown")
39
- }
40
- else:
41
- print(f"No data for {domain}")
42
- return {
43
- "domain": domain,
44
- "alexa_ranking": "unknown",
45
- "annual_revenue": "unknown",
46
- "country": "unknown",
47
- "estimated_num_employees": "unknown",
48
- "industry": "unknown",
49
- "keywords": "unknown",
50
- "linkedin_uid": "unknown"
51
- }
52
-
53
- @app.post("/get_data_file")
54
- def main(file: UploadFile = File(...)):
55
- LEAD_LIST_PATH = file.filename
56
- print(file.filename)
57
- with open(file.filename, "wb") as file_object:
58
- file_object.write(file.file.read())
59
-
60
- def get_domain(url):
61
- if "//" in url:
62
- start = url.index("//") + 2
63
- else:
64
- start = 0
65
- result = url[start:].strip("/")
66
- return result
67
 
68
- # Read the list of websites from the Excel file
69
- data = pd.read_excel(LEAD_LIST_PATH)
70
- websites = data[WEBSITE_COLUMN].drop_duplicates().apply(get_domain)
71
 
72
- # Fetch company data for each website
73
- company_data = []
74
- for website in websites:
75
- company_data.append(get_company_data(API_KEY, website))
76
-
77
- OUTPUT_PATH = "CompanyData.xlsx"
78
- # Create a DataFrame and save to Excel
79
- df = pd.DataFrame(company_data)
80
- df.to_excel(OUTPUT_PATH, index=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
- print("Company data has been successfully fetched and saved.")
83
- return FileResponse(OUTPUT_PATH, media_type='application/octet-stream', filename=OUTPUT_PATH)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
 
 
 
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
 
 
 
 
 
 
 
 
 
1
  import requests
2
+ from fastapi import FastAPI, Query
3
+ from fastapi.responses import FileResponse
4
+ import matplotlib.pyplot as plt
5
+ from datetime import datetime, timedelta
6
  import pandas as pd
7
+ from sklearn.linear_model import LinearRegression
8
+ from sklearn.preprocessing import StandardScaler
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ import uvicorn
11
+ from fastapi.responses import HTMLResponse
12
 
13
  app = FastAPI()
14
+
15
+ # Configure CORS
16
+ origins = [
17
+ "*", # Allows all origins
18
+ ]
19
+
20
  app.add_middleware(
21
  CORSMiddleware,
22
+ allow_origins=origins, # Allows all origins
23
  allow_credentials=True,
24
+ allow_methods=["*"], # Allows all methods
25
+ allow_headers=["*"], # Allows all headers
26
  )
 
 
 
27
 
28
+ # Constants for API access
29
+ API_KEY = 'U9ER11OA4VGEWV9K'
30
+ STOCK_SYMBOL = 'AAPL'
31
+ API_URL = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={STOCK_SYMBOL}&apikey={API_KEY}"
32
 
33
+ # Function to fetch stock data
34
+ def fetch_stock_data(symbol):
35
+ url = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey={API_KEY}"
36
+ response = requests.get(url)
37
+ data = response.json()
38
+ return data['Time Series (Daily)']
39
 
40
+ # Function to update stock data and plot
41
+ def fetch_and_update(symbol=STOCK_SYMBOL, graph_type="line"):
42
+ daily_data = fetch_stock_data(symbol)
43
 
44
+ dates = []
45
+ close_prices = []
46
+ for date, daily_info in sorted(daily_data.items()):
47
+ dates.append(datetime.strptime(date, '%Y-%m-%d'))
48
+ close_prices.append(float(daily_info['4. close']))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ plt.figure(figsize=(14, 7))
 
 
51
 
52
+ if graph_type == "line":
53
+ plt.plot(dates, close_prices, marker='o', linestyle='-')
54
+ elif graph_type == "bar":
55
+ plt.bar(dates, close_prices)
56
+ elif graph_type == "scatter":
57
+ plt.scatter(dates, close_prices)
58
+ elif graph_type == "buy_sell":
59
+ stock_data = pd.DataFrame({'Date': dates, 'Close': close_prices})
60
+ stock_data['Short_MA'] = stock_data['Close'].rolling(window=40).mean()
61
+ stock_data['Long_MA'] = stock_data['Close'].rolling(window=100).mean()
62
+
63
+ buy_signals = stock_data[(stock_data['Short_MA'] > stock_data['Long_MA']) & (stock_data['Short_MA'].shift(1) <= stock_data['Long_MA'].shift(1))].index
64
+ sell_signals = stock_data[(stock_data['Short_MA'] < stock_data['Long_MA']) & (stock_data['Short_MA'].shift(1) >= stock_data['Long_MA'].shift(1))].index
65
+
66
+ plt.plot(stock_data['Date'], stock_data['Close'], label='Closing Price', alpha=0.5)
67
+ plt.plot(stock_data['Date'], stock_data['Short_MA'], label='40-Day Moving Average', alpha=0.75)
68
+ plt.plot(stock_data['Date'], stock_data['Long_MA'], label='100-Day Moving Average', alpha=0.75)
69
+ plt.scatter(stock_data.loc[buy_signals]['Date'], stock_data.loc[buy_signals]['Close'], marker='^', color='g', label='Buy Signal', alpha=1)
70
+ plt.scatter(stock_data.loc[sell_signals]['Date'], stock_data.loc[sell_signals]['Close'], marker='v', color='r', label='Sell Signal', alpha=1)
71
+
72
+ plt.title(f'{symbol} Stock Prices Over Time')
73
+ plt.xlabel('Date')
74
+ plt.ylabel('Close Price ($)')
75
+ plt.gcf().autofmt_xdate()
76
+ plt.legend()
77
+ plt.savefig("stock.png") # Save the plot as a PNG file
78
+ plt.close()
79
+ return dates, close_prices
80
+
81
+ # Preprocess data for prediction
82
+ def preprocess_data(dates, close_prices):
83
+ df = pd.DataFrame({'Date': dates, 'Close': close_prices})
84
+ df['Date_ordinal'] = pd.to_datetime(df['Date']).apply(lambda date: date.toordinal())
85
 
86
+ # Handle missing values (if any)
87
+ df.fillna(method='ffill', inplace=True)
88
+ df.fillna(method='bfill', inplace=True)
89
+
90
+ # Feature scaling
91
+ scaler = StandardScaler()
92
+ df['Close_scaled'] = scaler.fit_transform(df[['Close']])
93
+
94
+ return df, scaler
95
+
96
+ # Machine Learning Model for Prediction
97
+ def predict_stock_prices(dates, close_prices, interval_days=7):
98
+ df, scaler = preprocess_data(dates, close_prices)
99
+
100
+ model = LinearRegression()
101
+ model.fit(df[['Date_ordinal']], df['Close_scaled'])
102
+
103
+ last_date = df['Date'].max()
104
+ future_dates = [last_date + timedelta(days=i) for i in range(1, interval_days+1)]
105
+ future_ordinal = [date.toordinal() for date in future_dates]
106
+ scaled_predictions = model.predict(pd.DataFrame(future_ordinal, columns=['Date_ordinal']))
107
+
108
+ predictions = scaler.inverse_transform(scaled_predictions.reshape(-1, 1)).flatten()
109
+
110
+ return future_dates, predictions
111
+
112
 
113
+ @app.get("/", response_class=HTMLResponse)
114
+ async def read_root():
115
+ html= open("index.html","r")
116
+ return HTMLResponse(content=html.read())
117
 
118
+ # FastAPI endpoint to serve the graph image
119
+ @app.get("/graph")
120
+ async def get_graph(symbol: str = STOCK_SYMBOL, graph_type: str = Query("line", enum=["line", "bar", "scatter", "buy_sell"])):
121
+ dates, close_prices = fetch_and_update(symbol, graph_type)
122
+ return FileResponse("stock.png")
123
+
124
+ # FastAPI endpoint to predict stock prices
125
+ @app.get("/predict")
126
+ async def predict(symbol: str = STOCK_SYMBOL, interval: int = 7):
127
+ dates, close_prices = fetch_and_update(symbol)
128
+ future_dates, predictions = predict_stock_prices(dates, close_prices, interval)
129
+
130
+ prediction_data = {str(date): float(pred) for date, pred in zip(future_dates, predictions)}
131
+ return prediction_data
132
 
133
+ # if __name__ == "__main__":
134
+ # # Run the FastAPI app using uvicorn with automatic reloading
135
+ # uvicorn.run(app, host="127.0.0.1", port=8000)