Skip to content

Instantly share code, notes, and snippets.

@RamonWill
Last active July 30, 2022 15:19
Show Gist options
  • Save RamonWill/d0435a5a344288a6f6646664e1604e95 to your computer and use it in GitHub Desktop.
Save RamonWill/d0435a5a344288a6f6646664e1604e95 to your computer and use it in GitHub Desktop.
Code from my second video on how to get stock prices from AlphaVantage create a Microsoft.Data.Analysis DataFrame from it
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Analysis;
using ServiceStack;
using ServiceStack.Text;
namespace StockPricesProject
{
// https://www.youtube.com/watch?v=0pTty4bYZC0
class Program
{
static void Main(string[] args)
{
AVConnection conn = new AVConnection("demo");
List<SecurityData> prices = conn.GetDailyPrices("IBM");
prices.Reverse();
PrimitiveDataFrameColumn<DateTime> date = new PrimitiveDataFrameColumn<DateTime>("Date", prices.Select(sd => sd.Timestamp));
PrimitiveDataFrameColumn<decimal> priceCol = new PrimitiveDataFrameColumn<decimal>("Close Price", prices.Select(sd => sd.Close));
DataFrame df = new DataFrame(date, priceCol);
PrimitiveDataFrameColumn<decimal> pctChange = new PrimitiveDataFrameColumn<decimal>("Percent Change", prices.Count);
for(int i=1; i < prices.Count; i++)
{
decimal prevPrice = (decimal)df.Columns["Close Price"][i - 1];
decimal currPrice = (decimal)df.Columns["Close Price"][i];
decimal delta = ((currPrice / prevPrice) - 1) * 100;
pctChange[i] = Math.Round(delta, 3);
}
df.Columns.Add(pctChange);
Console.WriteLine(df);
}
}
public class SecurityData
{
// more detail here: https://medium.com/@mark.holdt/alphavantage-and-c-1d560e690387
public DateTime Timestamp { get; set; }
public decimal Close { get; set; }
}
public class AVConnection
{
private readonly string _apiKey;
public AVConnection(string apiKey)
{
this._apiKey = apiKey;
}
public List<SecurityData> GetDailyPrices(string symbol)
{
const string FUNCTION = "TIME_SERIES_DAILY";
string connectionString = "https://" + $@"www.alphavantage.co/query?function={FUNCTION}&symbol={symbol}&apikey={this._apiKey}&datatype=csv";
List<SecurityData> prices = connectionString.GetStringFromUrl().FromCsv<List<SecurityData>>();
return prices;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment