Home > Mobile >  final output was not reflecting in csv, Need to fix output in data frame
final output was not reflecting in csv, Need to fix output in data frame

Time:05-19

Question - I need to get data from this given link and save as a csv format. Required data's are price, previous close, symbol.

I am a beginner, I don't know how to frame data, could pls help me with a reference code.

Any other alternative methods also fine.

#input data was given below
tikcer  = ['msft','amd','aapl']

Expecting output format-

A B C
0 261.5 266.82 MSFT
1 94.24 102.47 AMD
2 145.54 149.24 AAPL

I am getting this output -

A B C
0 145.54 149.24 AAPL

My testing code

import json
import requests
#import pyuser_agent
import pandas as pd
#ua = pyuser_agent.UA()
#headers = {'User-Agent': ua.random }
headers = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)' }
tikcer  = ['msft','amd','aapl']
for i in tikcer:
  print(i)
  url = f"https://query1.finance.yahoo.com/v8/finance/chart/{i}"
  response = requests.get(url, headers=headers)
  print("API is working. status code :"   str(response.status_code))
  datas = json.loads(response.text)
  for value in datas['chart']['result']:
    print(value)
    a = value['meta']['previousClose']
    b = value['meta']['regularMarketPrice']
    c = value['meta']['symbol']
    print(a,b,c)
    data = {'A': a, 'B': b, 'C': c}
    df = pd.DataFrame.from_dict([data])
    df.to_csv('data3.csv')
    #df = pd.DataFrame.from_dict({'A': [a], 'B': [b], 'C': [c]})
    #df.to_csv('data1.csv')

CodePudding user response:

At the beginning, a dataframe is created with NaN values (empty). And in the loop, each cell is filled, where df.loc[i, 'A'], i is the index of the row (on the left) and 'A' is the column name. Also, the loop is changed using range to access the indexes via i.

import json
import requests
#import pyuser_agent
import pandas as pd
#ua = pyuser_agent.UA()
#headers = {'User-Agent': ua.random }
headers = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)' }
tikcer  = ['msft','amd','aapl']
df = pd.DataFrame(index=[0, 1, 2], columns=['A', 'B', 'C'])

for i in range(0,len(tikcer)):
  print(tikcer[i])
  url = f"https://query1.finance.yahoo.com/v8/finance/chart/{tikcer[i]}"
  response = requests.get(url, headers=headers)
  print("API is working. status code :"   str(response.status_code))
  datas = json.loads(response.text)
  df.loc[i, 'A'] = datas['chart']['result'][0]['meta']['previousClose']
  df.loc[i, 'B'] = datas['chart']['result'][0]['meta']['regularMarketPrice']
  df.loc[i, 'C'] = datas['chart']['result'][0]['meta']['symbol']


print(df)

Output

        A        B     C
0   266.2   255.34  MSFT
1  102.47    96.89   AMD
2  149.24  141.809  AAPL
  • Related