我有以下代码
import requests
import json
import pandas as pd
from datetime import datetime
from datetime import timedelta
pd.options.display.float_format = '{:,.2f}'.format
url="https://nseindia.com/api/equity-stockIndices?index=SECURITIES%20IN%20F%26O"
headers = { "Accept-Encoding":"gzip, deflate","Accept-Language":"en-US,en;q=0.9",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36 OPR/65.0.3467.78"}
r=requests.get(url, headers=headers).json()
df1=pd.DataFrame().from_records(r['data'])
df2=df1[['symbol','dayHigh','dayLow','lastPrice','yearHigh','yearLow','previousClose','change','pChange']]
df2=df2.sort_values(['symbol'], ascending=True).reset_index(drop=True)
nifty1=df2.round(2)
nifty1
dt1 = '01-01-2020'
dt2 = '11-01-2020'
生成以下输出
symbol dayHigh dayLow lastPrice yearHigh yearLow previousClose change pChange
0 ACC 1525 1487.25 1510.8 1769.05 1326 1486.15 24.65 1.66
1 ADANIENT 213 205.9 210.5 221.5 113 208 2.50 1.20
2 ADANIPORTS 394.3 390 391.3 430.6 292.1 391.8 -0.50 -0.13
...
我有以下字符串
https://nseindia.com/api/historical/cm/equity?symbol=XXXX&series=["EQ"]&from=fromdt&to=todt
我想用 nifty1['symbol'] 列替换 XXXX,最好没有空格,用 dt1 和 dt2 fromdt 和 todt
例如。
https://nseindia.com/api/historical/cm/equity?symbol=ACC&series=["EQ"]&from=01-01-2020&to=11-01-2020
https://nseindia.com/api/historical/cm/equity?symbol=ADANIENT&series=["EQ"]&from=01-01-2020&to=11-01-2020
https://nseindia.com/api/historical/cm/equity?symbol=ADANIPORTS&series=["EQ"]&from=01-01-2020&to=11-01-2020
并存储到新的数据帧中
这是一种使用f-strings
的方法:
new_df = (df['symbol']
.apply(lambda x: f'https://nseindia.com/api/historical/cm/equity?symbol={x}&series=["EQ"]&from=fromdt&to=todt')
.to_frame())